如果我在下面的Scala中有这个代码:
val prices = Map("bread" -> 4.56, "eggs" -> 2.98, "butter" -> 4.35)
prices.map((k,v) => (k, v-1.1)).toMap
我收到错误:
The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (k, v) => ... }`
但是当我将第二行更改为:
prices.map{ case(k,v) => (k, v - 1.1) }.toMap
上述错误消失了吗?有人可以解释我何时需要在地图功能中使用案例?
答案 0 :(得分:1)
如@ chrisaycock的评论中所述,常规地图中没有自动解包。你需要像这样使用它:
scala> val prices = Map("bread" -> 4.56, "eggs" -> 2.98, "butter" -> 4.35)
prices: scala.collection.immutable.Map[String,Double] = Map(bread -> 4.56, eggs -> 2.98, butter -> 4.35)
scala> prices.map(kv => (kv._1, kv._2-1.1)).toMap
res0: scala.collection.immutable.Map[String,Double] = Map(bread -> 3.4599999999999995, eggs -> 1.88, butter -> 3.2499999999999996)