Search code examples
scalasetimmutable-collections

Scala immutable Set is mutable?


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?


Solution

  • 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.