Consider the following code that counts the frequency of each string in the list and stores the results in the mutable map. This works great, but I don’t understand where the += method is defined?! Is this some weird implicit conversion thing or what? I saw this code somewhere but it didn’t include an explanation for the +=.
val list = List("a", "b", "a")
val counts = new scala.collection.mutable.HashMap[String, Int]().withDefaultValue(0)
list.foreach(counts(_) += 1)
counts
//> res7: scala.collection.mutable.Map[String,Int] = Map(a -> 2, b -> 1)
The apply of map returns an Int, but Int doesn’t have a += and this method updates the map with a new value, so it looks as if the apply returns a mutable integer that has a += method…
This is not an implicit conversion – it is a desugaring.
Writing:
desugars to:
if the class of
xdoes not have a+=method defined on it.In the same way:
desugars to:
because
counts("a")is anInt, andIntdoes not have a+=method defined.On the other hand, writing:
desugars to a call to the
updatemethod in Scala:Every mutable
Maphas anupdatemethod defined – it allows setting keys in the map.So the entire expression is desugared to:
This
+=is not to be confused with the+=method onmutable.Maps in Scala. That method updates the entry in the map if that key already existed, or adds a new key-value pair. It returns thethisreference, that is, the same map, so you can chain+=calls. See ScalaDoc or the source code.