Scala Immutability
An immutable value never changes after it is created. Scala nudges you towards immutability at every level: val instead of var, case classes with read-only fields, and collections whose "updates" return new collections. This chapter explains why that is worth it and how to work comfortably with immutable data.
Why immutability?
| Benefit | Explanation |
|---|---|
| Easier reasoning | a value means the same thing everywhere it is used |
| Safe sharing | you can pass data to any function without defensive copies |
| Thread safety | immutable objects can be read from many threads with no locks |
| Simple equality and hashing | values are safe as map keys and set elements |
| Undo and history for free | old versions still exist after an "update" |
The problem with shared mutable state
import scala.collection.mutable.ArrayBuffer
def addDiscountItem(cart: ArrayBuffer[String]): ArrayBuffer[String] =
cart += "free sticker" // mutates the caller's cart!
cart
@main def run(): Unit =
val myCart = ArrayBuffer("book", "pen")
val promoCart = addDiscountItem(myCart)
println(promoCart)
println(myCart) // surprise: changed tooArrayBuffer(book, pen, free sticker)
ArrayBuffer(book, pen, free sticker)
The function's caller did not expect its own cart to change. With an immutable List, this bug is impossible:
def addDiscountItem(cart: List[String]): List[String] =
cart :+ "free sticker"
@main def run(): Unit =
val myCart = List("book", "pen")
val promoCart = addDiscountItem(myCart)
println(promoCart)
println(myCart)List(book, pen, free sticker)
List(book, pen)
Structural sharing
"Copying everything on every change" sounds slow, but immutable collections are designed to share most of their structure. Prepending to a List reuses the entire old list as the tail:
@main def run(): Unit =
val tail = List(2, 3, 4)
val a = 1 :: tail
val b = 0 :: tail
println(a)
println(b)
println(a.tail eq tail) // same object, not a copy
println(b.tail eq tail)List(1, 2, 3, 4)
List(0, 2, 3, 4)
true
true
Vector, Map and Set use trees for the same effect: an update copies only a small path of nodes.
Updating nested data
Case classes plus copy handle updates of nested immutable data. The trick is to copy each level on the way down.
case class Address(street: String, city: String)
case class Customer(name: String, address: Address, tags: Set[String])
@main def run(): Unit =
val c1 = Customer("Rui", Address("Main St 1", "Porto"), Set("new"))
val c2 = c1.copy(address = c1.address.copy(city = "Lisbon"))
val c3 = c2.copy(tags = c2.tags - "new" + "loyal")
println(c1)
println(c2)
println(c3)Customer(Rui,Address(Main St 1,Porto),Set(new))
Customer(Rui,Address(Main St 1,Lisbon),Set(new))
Customer(Rui,Address(Main St 1,Lisbon),Set(loyal))
All three versions exist side by side — a history for free.
Replacing loops with accumulators
Code that updates a var in a loop can usually be rewritten with foldLeft, where each step returns a new state.
case class Stats(count: Int, total: Double, max: Double):
def mean: Double = if count == 0 then 0 else total / count
@main def run(): Unit =
val readings = List(12.5, 19.0, 7.5, 21.0)
val stats = readings.foldLeft(Stats(0, 0, Double.MinValue)) { (s, r) =>
Stats(s.count + 1, s.total + r, s.max.max(r))
}
println(stats)
println(stats.mean)Stats(4,60.0,21.0)
15.0
When mutation is fine
Immutability is the default, not a law. Local mutation that never escapes a method is invisible to callers and can be faster:
def squares(n: Int): Vector[Int] =
val buf = scala.collection.mutable.ArrayBuffer.empty[Int]
var i = 1
while i <= n do
buf += i * i
i += 1
buf.toVector // callers only ever see an immutable VectorTip: A good rule: mutable inside, immutable at the boundary. If mutation is confined to one method and the result is immutable, nobody else can be surprised by it.
Immutable vs. mutable collections
| Immutable (default) | Mutable counterpart (scala.collection.mutable) |
|---|---|
List, Vector |
ArrayBuffer, ListBuffer |
Set |
mutable.Set |
Map |
mutable.Map |
String |
StringBuilder |
Test yourself
What happens to xs after val ys = xs :+ 4 when xs is a List?
xsnow ends with 4xsis unchangedxsis emptied- It does not compile
Why is prepending to an immutable List cheap?
- The list is copied in a background thread
- The new list reuses the old list as its tail (structural sharing)
- Lists are actually mutable
- The JVM optimises it away
Which approach updates a nested case class field immutably?
c.address.city = "X"c.copy(address = c.address.copy(city = "X"))c.setCity("X")c.address.copy(city = "X")alone