The docs say:
A collection in package scala.collection.immutable is guaranteed to be immutable for everyone. Such a collection will never change after it is created.
But I don't get the behavior I would expect from this:
scala> var test3 = scala.collection.immutable.Set[String]("one", "two") test3: scala.collection.immutable.Set[String] = Set(one, two) scala> test3 += "three" scala> println(test3) Set(one, two, three)
What am I missing here?
There are two things to avoid (if possible) when working with collections. Immutable collections, as you know, are preferred over mutable ones. However, having an immutable collection stored in a mutable variable only "delays" the problem. You moved the mutability along with all the problems it brings from the collection itself to the variable that holds the collection. Either way you have a state.
Ideal solution is to avoid both. That is, to use both immutable collections and immutable fields (vals). For example, a function can be producing an immutable collection and other function can be consuming it, without ever having to keep the collection itself somewhere or modifying it.
var can be reassigned (it is a variable, so it can vary). You are then no longer referencing the previous object at all.
val cannot be reassigned (it is a value, so it cannot vary), but you can call methods on that object, for example if the value is a
When I say vary I basically mean that the reference cannot vary. It's a bit confusing, I know.
To put it another way: both
vars can point to objects with internal state that itself can change. Like a mutable map.
I encourage you to write a code example yourself that verifies this table:
| MutableSet | ImmutableSet -------------------------------------------------- var | Reassign. Insert element | Reassign val | Insert | None of these