Scala Map foreach
Solution 1:
I'm not sure about the error, but you can achieve what you want as follows:
m.foreach(p => println(">>> key=" + p._1 + ", value=" + p._2))
That is, foreach
takes a function that takes a pair and returns Unit
, not a function that takes two arguments: here, p
has type (String, Int)
.
Another way to write it is:
m.foreach { case (key, value) => println(">>> key=" + key + ", value=" + value) }
In this case, the { case ... }
block is a partial function.
Solution 2:
oops, read the doco wrong, map.foreach expects a function literal with a tuple argument!
so
m.foreach((e: (String, Int)) => println(e._1 + "=" + e._2))
works
Solution 3:
You need to patter-match on the Tuple2
argument to assign variables to its subparts key
, value
. You can do with very few changes:
m.foreach{ case (key: String, value: Int) => println(">>> key=" + key + ", value=" + value)}
Solution 4:
The confusing error message is a compiler bug, which should be fixed in 2.9.2: