Dzh*_*zhu 48 scala scala-collections
给定:
val m = Map[String, Int]("a" -> 1, "b" -> 2, "c" -> 3)
m.foreach((key: String, value: Int) => println(">>> key=" + key + ", value=" + value))
Run Code Online (Sandbox Code Playgroud)
为什么编译器会抱怨
error: type mismatch
found : (String, Int) => Unit
required: (String, Int) => ?
Run Code Online (Sandbox Code Playgroud)
Phi*_*ppe 75
我不确定错误,但你可以实现你想要的如下:
m.foreach(p => println(">>> key=" + p._1 + ", value=" + p._2))
Run Code Online (Sandbox Code Playgroud)
也就是说foreach,采用一对并返回Unit的函数,而不是一个带有两个参数的函数:这里p有类型(String, Int).
另一种写作方式是:
m.foreach { case (key, value) => println(">>> key=" + key + ", value=" + value) }
Run Code Online (Sandbox Code Playgroud)
在这种情况下,{ case ... }块是部分功能.
Dzh*_*zhu 29
oops,读取doco错误,map.foreach期望一个带有元组参数的函数文字!
所以
m.foreach((e: (String, Int)) => println(e._1 + "=" + e._2))
Run Code Online (Sandbox Code Playgroud)
作品
hui*_*ker 15
您需要对Tuple2参数进行模式匹配,以将变量分配给其子部分key,value.你可以做很少的改变:
m.foreach{ case (key: String, value: Int) => println(">>> key=" + key + ", value=" + value)}
Run Code Online (Sandbox Code Playgroud)
好问题!即使明确键入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)}
^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62090 次 |
| 最近记录: |