4.3 Updating Map Values
In this section, we discuss mutable maps. Here is how to construct one:
val scores = scala.collection.mutable.Map("Alice" -> 10, "Bob" -> 3, "Cindy" -> 8)
In a mutable map, you can update a map value, or add a new one, with a () to the left of an = sign:
scores("Bob") = 10 // Updates the existing value for the key "Bob" (assuming scores is mutable) scores("Fred") = 7 // Adds a new key/value pair to scores (assuming it is mutable)
Alternatively, you can use the ++= operator to add multiple associations:
scores ++= Map("Bob" -> 10, "Fred" -> 7)
To remove a key and its associated value, use the -= operator:
scores -= "Alice"
You can’t update an immutable map, but you can do something that’s just as useful—obtain a new map that has the desired update:
val someScores = Map("Alice" -> 10, "Bob" -> 3) val moreScores = someScores + ("Cindy" -> 7) // Yields a new immutable map
The moreScores map contains the same associations as someScores, as well as a new association for the key "Cindy".
Instead of saving the result as a new value, you can update a var:
var currentScores = moreScores currentScores = currentScores + ("Fred" -> 0)
You can even use the += operator:
currentScores += "Donald" -> 5
Similarly, to remove a key from an immutable map, use the - operator to obtain a new map without the key:
currentScores = currentScores - "Alice"
or
currentScores -= "Alice"
You might think that it is inefficient to keep constructing new maps, but that is not the case. The old and new maps share most of their structure. (This is possible because they are immutable.)