typestar

Copy updates in Scala

Kiln firings revised with copy, which builds a new value and leaves the old one alone.

// every case class gets a copy method for immutable updates
case class Firing(kiln: String, cone: Int, hours: Int)
val bisque: Firing = Firing("Anagama", 6, 9)

// name only the fields that change; the rest are carried over
val hotter: Firing = bisque.copy(cone = 10)

// the source value is untouched, which is what makes this safe
val originalCone: Int = bisque.cone

// copies chain, each call producing another independent value
val glaze: Firing = bisque.copy(cone = 10).copy(hours = 14)

// the fields left alone still compare equal to the source
val sameKiln: Boolean = glaze.kiln == bisque.kiln
val differs: Boolean = glaze != bisque

// copy with no arguments carries every field over, so it is equal
val duplicate: Firing = bisque.copy()
val equalPair: Boolean = duplicate == bisque

How it works

  1. bisque.copy(cone = 10) names the single field that changes, carrying kiln and hours over untouched.
  2. bisque.cone still reads its original value afterwards, and bisque.copy(cone = 10).copy(hours = 14) chains two copies into a third independent value.
  3. glaze.kiln == bisque.kiln holds for the field left alone while glaze != bisque holds for the whole, and bisque.copy() carries every field over so duplicate == bisque.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
793
Tokens
114
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 2 of 3 in Case classes & enums, step 17 of 27 in Language basics.

← Previous Next →