Scala 地图 foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8610776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala Map foreach
提问by Dzhu
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) => ?
采纳答案by Dzhu
oops, read the doco wrong, map.foreach expects a function literal with a tuple argument!
哎呀,读错了 doco,map.foreach 需要一个带有元组参数的函数文字!
so
所以
m.foreach((e: (String, Int)) => println(e._1 + "=" + e._2))
works
作品
回答by Philippe
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, foreachtakes a function that takes a pair and returns Unit, not a function that takes two arguments: here, phas type (String, Int).
也就是说,foreach接受一个接受一对并返回Unit的函数,而不是接受两个参数的函数:这里p有类型(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.
在这种情况下,{ case ... }块是一个偏函数。
回答by Francois G
You need to patter-match on the Tuple2argument to assign variables to its subparts key, value. You can do with very few changes:
您需要对Tuple2参数进行模式匹配以将变量分配给其子部分key, value。您只需进行很少的更改即可:
m.foreach{ case (key: String, value: Int) => println(">>> key=" + key + ", value=" + value)}
回答by Paul Butcher
The confusing error message is a compiler bug, which should be fixed in 2.9.2:
令人困惑的错误消息是编译器错误,应在 2.9.2 中修复:
回答by Eishay Smith
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.
好问题!即使明确键入 foreach 方法,它仍然会给出非常不清楚的编译错误。有很多方法可以解决,但我不明白为什么这个例子不起作用。
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)}
^
回答by vikashait
Docs says argument is tuple -> unit, so We can easily do this
文档说参数是元组 -> 单位,所以我们可以很容易地做到这一点
Map(1 -> 1, 2 -> 2).foreach(tuple => println(tuple._1 +" " + tuple._2)))
回答by Yaroslav
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.
但是它需要显式类型注释,所以我更喜欢部分函数。

