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
bisque.copy(cone = 10)names the single field that changes, carryingkilnandhoursover untouched.bisque.conestill reads its original value afterwards, andbisque.copy(cone = 10).copy(hours = 14)chains two copies into a third independent value.glaze.kiln == bisque.kilnholds for the field left alone whileglaze != bisqueholds for the whole, andbisque.copy()carries every field over soduplicate == bisque.
Keywords and builtins used here
BooleanFiringIntStringcaseclassval
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.
Step 2 of 3 in Case classes & enums, step 17 of 27 in Language basics.