10

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?

Eugene Yokota
  • 94,654
  • 45
  • 215
  • 319
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449

2 Answers2

14

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".)

starblue
  • 55,348
  • 14
  • 97
  • 151
  • Could you point me to the page in Programming in Scala; unless I'm being blind I can't find it. I'm really not convinced that this is syntactic sugar at all – oxbow_lakes Mar 25 '09 at 10:59
  • Can you indicate where the "update" method is in the hierarchy? I can't even find it! – oxbow_lakes Mar 25 '09 at 11:33
  • That's the bit in "Programming in Scala" which says that m("Hello") = 5 is equivalent to m.update("Hello", 5). But I can't actually see that Map has a method "update" on it. – oxbow_lakes Mar 26 '09 at 13:08
5

@starblue is correct. Note that you can also do rather creative things with update such as returning values other than what was assigned. For example:

val a = Map(1 -> "one")      // an immutable Map[Int, String]
val b = a(2) = "two"
val c = b(5) = "five"
val d = c(1) = "uno"

d == Map(1 -> "uno", 2 -> "two", 5 -> "five")       // => true

This works because immutable.Map#update returns an instance of the new Map. It looks a little odd to the C-trained eye, but you get used to it.

Daniel Spiewak
  • 54,515
  • 14
  • 108
  • 120
  • 3
    So "m(K) = V" is syntactic sugar for m.update(K, V). How can one tell that this is the case? What other methods may have syntactic sugar applied to them? And I can't even see a method update on Map (or any of its inheritees) in the scaladoc. How would I even know that Map had such a method? – oxbow_lakes Mar 25 '09 at 11:32