Scala Map: mysterious syntactic sugar?

oxbow_lakes picture oxbow_lakes · Mar 25, 2009 · Viewed 11.7k times · Source

I have just found out this syntax for a scala Map (used here in mutable form)

val m = scala.collection.mutable.Map[String, Int]()
m("Hello") = 5
println(m) //PRINTS Map(Hello -> 5)

Now I'm not sure whether this is syntactic sugar built in to the language, or whether something more fundamental is going on here involving the fact that a map extends a PartialFunction. Could anyone explain?

Answer

starblue picture starblue · Mar 25, 2009

If you mean (it would be nice if you could be more explicit)

m("Hello") = 5

that is intended syntactic sugar for

m.update("Hello", 5)

independent of what m is. This is analogous to

m("Hello")

which is syntactic sugar for

m.apply("Hello")

(I'm just reading "Programming in Scala".)