withDefaultValue 不适用于 2.12.3 中的 immutable.Map

use*_*791 1 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>
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

che*_*ohi 5

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

get, contains, iterator, keys,

所以对于你的例子,你应该使用scores1("aaa")for get 0