Scala Map foreach

蹲街弑〆低调 提交于 2019-12-04 07:52:29

问题


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) => ?

回答1:


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.




回答2:


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




回答3:


You need to patter-match on the Tuple2 argument to assign variables to its subparts key, value. You can do with very few changes:

m.foreach{ case (key: String, value: Int) => println(">>> key=" + key + ", value=" + value)} 



回答4:


The confusing error message is a compiler bug, which should be fixed in 2.9.2:




回答5:


Excellent question! Even when explicitly typing the foreach method, it still gives that very unclear compile error. There are ways around it, but I can't 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)}
                                                         ^



回答6:


Docs says argument is tuple -> unit, so We can easily do this

Map(1 -> 1, 2 -> 2).foreach(tuple => println(tuple._1 +" " + tuple._2)))



回答7:


Yet another way:

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

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



来源:https://stackoverflow.com/questions/8610776/scala-map-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!