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

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) => ? 
+43
scala scala-collections
Dec 22 '11 at 23:17
source share
7 answers

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

+25
Dec 22 '11 at 23:31
source share

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.

+70
Dec 22 '11 at 23:22
source share

A confusing error message is a compiler error that should be fixed in 2.9.2 :

+14
Dec 23 '11 at 1:29
source share

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)} 
+13
Dec 22 '11 at 23:30
source share

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)} ^ 
+5
Dec 22 '11 at 23:51
source share

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))) 
+1
Jul 05 '15 at 23:12
source share

Another way:

 Map(1 -> 1, 2 -> 2).foreach(((x: Int, y: Int) => ???).tupled) 

However, this requires explicit type annotations, so I prefer partial functions.

0
Sep 27 '13 at 10:43 on
source share



All Articles