Sorry guys, I recently saw an example in "Programming in Scala", 2nd Edition on page 685, which seemed strange to me:
var hashSet: Set[C] = new collection.immutable.HashSet hashSet += elem1 How is it possible to add something an immutable collection? I tried on REPL and it worked ok!
> scala Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11). Type in expressions to have them evaluated. Type :help for more information. scala> var s : Set[Int] = collection.immutable.HashSet() s: Set[Int] = Set() scala> s += 1324 scala> println(s) Set(1324) The stranger fact is that += operator is not defined in immutable.HashSet api page. Could anybody please help me understand what's going on?
Thanks.
+=is handled syntax-wise, but adding to an immutable HashSet is just like appending to an immutable String: You get a new instance with the modified contents.