Scala Map foreach

Dzhu picture Dzhu · Dec 23, 2011 · Viewed 66.1k times · Source

given:

val m = Map[String, Int]("a" -> 1, "b" -> 2, "c" -> 3)
m.foreach((key: String, value: Int) => println(">>> key=" + key + ", value=" + value))

why does the compiler complain

error: type mismatch
found   : (String, Int) => Unit
required: (String, Int) => ?

Answer

Philippe picture Philippe · Dec 23, 2011

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.