我正在尝试使用foldl将列表中的对添加到地图中.我收到以下错误:
"missing arguments for method /: in trait TraversableOnce; follow this method with `_' if you want to treat it as a partially applied function"
Run Code Online (Sandbox Code Playgroud)
码:
val pairs = List(("a", 1), ("a", 2), ("c", 3), ("d", 4))
def lstToMap(lst:List[(String,Int)], map: Map[String, Int] ) = {
(map /: lst) addToMap ( _, _)
}
def addToMap(pair: (String, Int), map: Map[String, Int]): Map[String, Int] = {
map + (pair._1 -> pair._2)
}
Run Code Online (Sandbox Code Playgroud)
怎么了?
mis*_*tor 10
scala> val pairs = List(("a", 1), ("a", 2), ("c", 3), ("d", 4))
pairs: List[(String, Int)] = List((a,1), (a,2), (c,3), (d,4))
scala> (Map.empty[String, Int] /: pairs)(_ + _)
res9: scala.collection.immutable.Map[String,Int] = Map(a -> 2, c -> 3, d -> 4)
Run Code Online (Sandbox Code Playgroud)
但是你知道,你可以做到:
scala> pairs.toMap
res10: scala.collection.immutable.Map[String,Int] = Map(a -> 2, c -> 3, d -> 4)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1074 次 |
| 最近记录: |