Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 672
Dan Midwood Avatar asked Mar 24 '13 22:03

Dan Midwood


People also ask

How do you add a mutable map?

Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.

How do I add values to a map in Scala?

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.

What is mutable map in Scala?

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.

Is map mutable or immutable?

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.


1 Answers

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.

like image 200
Boris the Spider Avatar answered Oct 05 '22 13:10

Boris the Spider