scala's mutable and immutable set when to use val and var

The advantage of immutable data structures, in this case Set, is that they are persistent. For example:

var jetSet1 = Set("Boeing", "Airbus")
val jetSet2 = jetSet1 // ... imagine jetSet2 is somewhere else in the program
jetSet1 += "Lear"
assert(!jetSet2.contains("Lear"))

Immutability of these Set objects makes it easier to reason about the program because updates to the jetSet1 variable don't have side effects in other parts of the code (in this case, wherever jetSet2 is used). Although it's not clear from this example, there are occasions when it's convenient to store immutable values in mutable var references; most often, the var will have a limited scope (e.g., local to a function).

Immutable data structures often have clever implementations that are quite efficient. Unfortunately, the Scala collection API is not well documented regarding performance, but I would expect most operations to be roughly O(log N) time. For example, given a large immutable Set s, one should be able to efficiently construct s + x, a new Set with an extra element. Of course, immutability guarantees that s is also preserved. Under the hood, s and s+x will be stored using some kind of tree data-structures with shared components.

The title of your question suggest you are also looking for advice about using val or var. The rule of thumb is to use val whenever you can conveniently. If a var is necessary, then try to limit the variable's scope as much as possible.


var allows you to reassign to a variable, think of it as a normal variable declaration in Java. But in the above case, even though you are reassigning to the same variable, it's always a different set since you are using an immutable one.

The point of the example was to show that even if you try "modifying" an immutable collection, the modifications create a new collection instead of touching the original one. If the author would have used a val (along the lines of final in Java), he would have to introduce a variable in scope to hold the new immutable set. I think var was probably used to keep the example simple.

Tags:

Scala