"tim") age_list.foreach { age => queryMap += ("age" -> age.toString) } If" /> "tim") age_list.foreach { age => queryMap += ("age" -> age.toString) } If" /> "tim") age_list.foreach { age => queryMap += ("age" -> age.toString) } If"/>

Placeholder in Scala function doesnt work with mutable Maps

96 Views Asked by At

I have the following code in Scala which works:

var queryMap = Map("name" -> "tim")
age_list.foreach { age => queryMap += ("age" -> age.toString) }

If I include placeholders in the function, it breaks:

var queryMap = Map("name" -> "tim")
age_list.foreach { queryMap += ("age" -> _.toString) }   

The following error is thrown:

value += is not a member of scala.collection.immutable.Map[String,String] 

queryMap becomes an immutable Map instead of a mutable Map. Is there something wrong with my syntax structure?

1

There are 1 best solutions below

1
Mikaël Mayer On BEST ANSWER

_ I cannot reproduce this error, I get a different one:

error: missing parameter type for expanded function ((x$1: <error>) => "age".$minus$greater(x$1.toString))

Which means that the underscore is not bound to the foreach, but to after the +=. Underscores are bound inside parentheses, if there are any. Hence you can remove them and it will work.

var queryMap = Map("name" -> "tim")
age_list.foreach { queryMap += "age" -> _.toString }