Skip to Content
Course content

18: Immutability and Persistent Collections

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent more hours than I care to admit debugging "ghost" changes in large systems—situations where a piece of data was modified in one part of the application, and suddenly a completely unrelated module started crashing because its state had shifted under its feet. In Scala, the primary defense against this is immutability, specifically through the use of persistent collections.

The Headache of the Shared Mutable Set

Let's look at a common scenario: managing user permissions. If you're coming from Java or Python, your instinct might be to use a mutable set to keep track of a user's roles. It feels efficient. You just add or remove strings as the user's status changes.

import scala.collection.mutable

case class User(name: String, permissions: mutable.Set[String])

val admin = User("Alice", mutable.Set("read", "write"))
val currentPermissions = admin.permissions

// Some deep in the call stack, a validation function does this:
def checkAndCleanPermissions(perms: mutable.Set[String]): Unit = {
  if (perms.contains("debug")) {
    perms.remove("debug") // Mutating the original set!
  }
}

The problem here isn't the remove call itself; it's that currentPermissions and admin.permissions point to the exact same object in memory. If you pass that set to a logging service, a validation engine, or a background thread, any one of them can change the state of your User object without the User object ever knowing. You lose the ability to reason about your program because the state is "leaking." To fix this with mutable collections, you'd have to defensively copy the set every time you passed it to a function, which is tedious and surprisingly slow.

Structural Sharing: Getting the Best of Both Worlds

Now, you might be thinking: "If I use an immutable set, won't Scala copy the entire collection every time I add a single permission?" If that were true, immutable collections would be a performance nightmare. But Scala uses persistent data structures.

When you "add" an element to an immutable collection, Scala doesn't copy the whole thing. Instead, it creates a new version of the collection that shares as much of the original structure as possible. This is called structural sharing. If you have a large tree-based set and add one element, the new set will simply point to most of the old tree and add one new node.

case class User(name: String, permissions: Set[String]) // Default is immutable

val admin = User("Alice", Set("read", "write"))
val updatedAdmin = admin.copy(permissions = admin.permissions + "execute")

// admin.permissions is still Set("read", "write")
// updatedAdmin.permissions is Set("read", "write", "execute")

In this version, admin remains untouched. You have a perfect snapshot of the user's state at a specific point in time. If a background thread is still processing the old admin object, it doesn't matter that you created updatedAdmin; the thread's view of the world remains consistent. The cost of the + operation is logarithmic rather than linear, making it incredibly efficient for the safety it provides.

Picking Your Poison

I'll be honest with you: there are times when mutability is the right choice. If you're inside a tight loop performing millions of updates to a local buffer that never leaves the scope of a single function, a mutable.ArrayBuffer will outperform an immutable List. The key is containment.

The rule of thumb I follow is this: keep your public APIs, your case classes, and your shared state strictly immutable. If you absolutely need mutability for performance, wrap it inside a function so that the mutation is invisible to the rest of the system. The caller provides an immutable collection, you convert it to a mutable one internally, do your heavy lifting, and return a new immutable collection. This gives you the speed of mutation with the sanity of immutability.




📋 Practical Task

Implementing a Versioned Undo-History for a Text Buffer

Imagine you are building a simple text editor. Instead of overwriting the current text, you want to keep a history of every change so the user can "undo" their work. Using a mutable string or a mutable list would make this difficult because you'd have to manually copy the text every time.

Your Task:

  • Create a case class EditorState that holds a String called content.
  • Create a class TextEditor that maintains a List[EditorState] called history. This list should be immutable.
  • Implement a method typeText(newText: String): Unit (or return a new instance of TextEditor) that prepends the current state to the history and updates the current content.
  • Implement a method undo(): Option[EditorState] that removes the most recent state and returns the previous one.
  • Demonstrate that adding text to the editor doesn't destroy the previous versions of the document.

Hint: Since the history is a List, remember that prepending an element (::) is an O(1) operation and leverages structural sharing.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.