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) => ?
Scala Map foreach() method with exampleThe foreach() method is utilized to apply the given function to all the elements of the map. Return Type: It returns all the elements of the map after applying the given function to each of them. So, the identical elements are taken only once.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With