Jack Daniel's Jack Daniel's - 2 months ago 7
Scala Question

Scala Sets Immutability

scala> var immSet = Set("A", "B")
immSet: scala.collection.immutable.Set[String] = Set(A, B)

scala> immSet += "C"

scala> println(immSet)
Set(A, B, C)


I wonder, what is the advantage I am getting by allowing
var
to be used with with an immutable Set? Am I not losing immutability in this case?

Answer

What is the advantage I am getting by allowing var to be used with with a Immutabable Sets?

I would say this can mainly cause confusion. The fact that you're using a var allows you to overwrite the variable, but, the Set by itself doesn't change, it allocates a new set with the additional value "C". But since you're using a var, the previous Set is now no longer referenced, unless you've referenced is somewhere else higher up the stack:

scala> var firstSet = Set("A", "B")
firstSet: scala.collection.immutable.Set[String] = Set(A, B)

scala> var secondSet = firstSet
secondSet: scala.collection.immutable.Set[String] = Set(A, B)

scala> firstSet += "C"

scala> firstSet
res6: scala.collection.immutable.Set[String] = Set(A, B, C)

scala> secondSet
res7: scala.collection.immutable.Set[String] = Set(A, B)

Because secondSet still points to the Set created by firstSet, we don't see the value update reflected. I think making this immutable adds clarity that the underlying Set is immutable and well as the variable pointing to it. When you use a val, the compiler will yell if you attempt to reassign, forcing you to realize that a new collection is initialized.

Regarding immutability, we need to divide this into two. There is the immutability of the Set, and there is the immutability of the variable pointing to that Set, these are two different things. You lose the latter with this approach.

Comments