20.2. Prefer Immutable Objects

Problem

You want to reduce the use of mutable objects and data structures in your code.

Solution

Begin with this simple philosophy, stated in the book, Programming in Scala:

“Prefer 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 List and Vector before reaching for the mutable ArrayBuffer.

  • Prefer immutable variables. That is, prefer val to var.

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 by the trustMeMuHaHa method is marked as final, the method can still mutate the collection:

// java

class EvilMutator {

  // trust me ... mu ha ha (evil laughter)
  public static void trustMeMuHaHa(final List<Person> people) {
    people.clear();
  }

}

Although Scala treats method arguments as vals, you leave yourself open to the exact same problem by passing around a mutable collection, like an ArrayBuffer:

def evilMutator(people: ArrayBuffer[Person]) {
  people.clear()
}

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

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.