20.2. Prefer Immutable Objects
You want to reduce the use of mutable objects and data structures in your code.
Begin with this simple philosophy, stated in the book, Programming in Scala:
vals, immutable objects, and methods without side effects. Reach for them first.”
Then use other approaches with justification.
There are two components to “prefer immutability”:
Prefer immutable collections. For instance, use immutable sequences like
Vectorbefore reaching for the mutable
Prefer immutable variables. That is, prefer
In Java, mutability is the default, and it can lead to
unnecessarily dangerous code and hidden bugs. In the following example,
even though the
List parameter taken
trustMeMuHaHa method is marked
final, the method can still mutate
// trust me ... mu ha ha (evil laughter)
Although Scala treats method arguments as
vals, you leave yourself open to the exact
same problem by passing around a mutable collection, like an
Just as with the Java code, the
evilMutator method can call
clear because the contents of an
ArrayBuffer are mutable.
Though nobody would write malicious code like this intentionally, accidents do happen. To make your code safe from this problem, if there’s no reason for a collection to be changed, don’t ...