Scala 的可变 Map 更新 [map(key) = newValue] 语法如何工作? [英] How does Scala's mutable Map update [map(key) = newValue] syntax work?
问题描述
我正在研究 Cay Horstmann 的 Scala 以编写不耐烦的书,在那里我遇到了这种更新可变地图的方式.
I'm working through Cay Horstmann's Scala for the Impatient book where I came across this way of updating a mutable map.
scala> val scores = scala.collection.mutable.Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
scores: scala.collection.mutable.Map[String,Int] = Map(Bob -> 3, Alice -> 10, Cindy -> 8)
scala> scores("Alice") // retrieve the value of type Int
res2: Int = 10
scala> scores("Alice") = 5 // Update the Alice value to 5
scala> scores("Alice")
res4: Int = 5
看起来 scores("Alice")
在 MapLike.scala
中点击了 apply
.但这只是返回值,而不是可以更新的东西.
It looks like scores("Alice")
hits apply
in MapLike.scala
. But this only returns the value, not something that can be updated.
出于好奇,我在不可变映射上尝试了相同的语法,但出现以下错误,
Out of curiosity I tried the same syntax on an immutable map and was presented with the following error,
scala> val immutableScores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
immutableScores: scala.collection.immutable.Map[String,Int] = Map(Alice -> 10, Bob -> 3, Cindy -> 8)
scala> immutableScores("Alice") = 5
<console>:9: error: value update is not a member of scala.collection.immutable.Map[String,Int]
immutableScores("Alice") = 5
^
基于此,我假设 scores("Alice") = 5
被转换为 scores update ("Alice", 5)
但我没有了解它是如何工作的,或者它是如何实现的.
Based on that, I'm assuming that scores("Alice") = 5
is transformed into scores update ("Alice", 5)
but I have no idea how it works, or how it is even possible.
它是如何工作的?
推荐答案
这是apply
、update
语法的示例.
当您调用 map("Something")
时,它会调用 map.apply("Something")
,后者又调用 get
.
When you call map("Something")
this calls map.apply("Something")
which in turn calls get
.
当您调用 map("Something") = "SomethingElse"
时,这会调用 map.update("Something", "SomethingElse")
,后者又调用 放置代码>.
When you call map("Something") = "SomethingElse"
this calls map.update("Something", "SomethingElse")
which in turn calls put
.
看看这个更全面的解释.
这篇关于Scala 的可变 Map 更新 [map(key) = newValue] 语法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!