withDefaultValue不适用于2.12.3中的immutable.Map

时间:2017-08-10 02:35:49

标签: scala

我在Scala 2.12.3中,看起来像withDefaultMethod不起作用。如果None

中没有该条目,我仍然会收到Map
> console
[info] Starting scala interpreter...
[info]
Welcome to Scala 2.12.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_141).
Type in expressions for evaluation. Or try :help.

scala> val scores = Map("Alice" -> 100, "Bob" -> 80, "Cindy" -> 99)
scores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 100, Bob -> 80, Cindy -> 99)

scala> val scores1 = scores.withDefaultValue(0)
scores1: scala.collection.immutable.Map[String,Int] = Map(Alice -> 100, Bob -> 80, Cindy -> 99)

scala> val aaaScore = scores1.get("aaa")
aaaScore: Option[Int] = None

scala>

我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

由于文档默认值不会影响,withDefaultValue

  

getcontainsiteratorkeys

因此,对于您的示例,您应该使用scores1("aaa")来获取0