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
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 ^
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.
How does it work?
Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.
Adding new key-value pair We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed. By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala.
The map is an immutable collection, so its methods only support the read-only access to the map. For creating a mutable map with read-write methods, you may use the MutableMap interface.
This is an example of the apply
, update
syntax.
When you call map("Something")
this calls map.apply("Something")
which in turn calls get
.
When you call map("Something") = "SomethingElse"
this calls map.update("Something", "SomethingElse")
which in turn calls put
.
Take a look at this for a fuller explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With