Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Map foreach

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) => ? 
like image 277
Dzhu Avatar asked Dec 22 '11 23:12

Dzhu


People also ask

How does foreach work in Scala?

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.


2 Answers

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.

like image 101
Philippe Avatar answered Sep 20 '22 09:09

Philippe


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

like image 27
Dzhu Avatar answered Sep 20 '22 09:09

Dzhu