How does Scala's mutable Map update [map(key) = newValue] syntax work?

Dan Midwood picture Dan Midwood · Mar 24, 2013 · Viewed 26.3k times · Source

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?

Answer

Boris the Spider picture Boris the Spider · Mar 24, 2013

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.