Scala foreach map
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) => ? oops, read doco wrong, map.foreach expects a function literal with a tuple argument!
So
m.foreach((e: (String, Int)) => println(e._1 + "=" + e._2)) work
I am not sure about the error, but you can achieve what you want:
m.foreach(p => println(">>> key=" + p._1 + ", value=" + p._2)) That is, foreach takes a function that takes a pair and returns Unit , and not a function that takes two arguments: here p is of type (String, Int) .
Another way to write this:
m.foreach { case (key, value) => println(">>> key=" + key + ", value=" + value) } In this case, the { case ... } block is a partial function.
A confusing error message is a compiler error that should be fixed in 2.9.2 :
For the Tuple2 argument Tuple2 you need to match patter-match to assign variables to your key , value substrings. You can make very few changes:
m.foreach{ case (key: String, value: Int) => println(">>> key=" + key + ", value=" + value)} Great question! Even with the explicit input of the foreach method, it still gives a very obscure compilation error. There are ways around this, but I cannot understand why this example does not work.
scala> m.foreach[Unit] {(key: String, value: Int) => println(">>> key=" + key + ", value=" + value)} <console>:16: error: type mismatch; found : (String, Int) => Unit required: (String, Int) => Unit m.foreach[Unit] {(key: String, value: Int) => println(">>> key=" + key + ", value=" + value)} ^ Docs says the argument is tuple -> unit, so we can easily do this
Map(1 -> 1, 2 -> 2).foreach(tuple => println(tuple._1 +" " + tuple._2))) Another way:
Map(1 -> 1, 2 -> 2).foreach(((x: Int, y: Int) => ???).tupled) However, this requires explicit type annotations, so I prefer partial functions.