Scala Case Classes
A case class is a class designed to hold immutable data. Add the word case and the compiler writes a lot of useful code for you: value-based equality, a readable toString, a copy method, a companion apply, and support for pattern matching. Case classes are the main tool for modelling data in Scala.
What you get for free
case class Point(x: Int, y: Int)
@main def run(): Unit =
val a = Point(1, 2)
val b = Point(1, 2)
println(a)
println(a == b)
println(a.x + a.y)
val moved = a.copy(y = 10)
println(moved)
println(Set(a, b, moved).size)Point(1,2)
true
3
Point(1,10)
2
| Feature | What it means |
|---|---|
val parameters |
every constructor parameter is a public, read-only field |
toString |
prints Point(1,2) |
equals / hashCode |
compares by field values, works in sets and as map keys |
copy(...) |
a new instance with some fields changed |
apply |
create instances without new |
unapply |
take instances apart in pattern matches |
Immutable updates with copy
Case class fields cannot be reassigned. To "change" an object, create a modified copy. The original stays the same, which makes data safe to share.
case class Account(owner: String, balance: BigDecimal, frozen: Boolean = false)
def deposit(acc: Account, amount: BigDecimal): Account =
if acc.frozen then acc else acc.copy(balance = acc.balance + amount)
@main def run(): Unit =
val start = Account("Ivo", BigDecimal("10.00"))
val after = deposit(start, BigDecimal("2.50"))
val frozen = after.copy(frozen = true)
println(start)
println(after)
println(deposit(frozen, BigDecimal("100")))Account(Ivo,10.00,false)
Account(Ivo,12.50,false)
Account(Ivo,12.50,true)
Pattern matching on case classes
Case classes can be taken apart in match expressions, including nested ones.
case class Address(city: String, country: String)
case class Customer(name: String, age: Int, address: Address)
def greeting(c: Customer): String = c match
case Customer(name, _, Address(_, "Japan")) => s"Konnichiwa, $name"
case Customer(name, age, _) if age < 18 => s"Hi $name!"
case Customer(name, _, Address(city, _)) => s"Hello $name from $city"
@main def run(): Unit =
println(greeting(Customer("Aiko", 30, Address("Osaka", "Japan"))))
println(greeting(Customer("Tim", 12, Address("Leeds", "UK"))))
println(greeting(Customer("Lea", 45, Address("Graz", "Austria"))))Konnichiwa, Aiko
Hi Tim!
Hello Lea from Graz
Modelling alternatives with sealed traits
A sealed trait can only be extended in the same file, so the compiler knows every possible subtype. Combined with case classes this models "one of several shapes" — and the compiler warns you if a match forgets one.
sealed trait Payment
case class Card(number: String) extends Payment
case class BankTransfer(iban: String) extends Payment
case object Cash extends Payment
def fee(p: Payment, amount: Double): Double = p match
case Card(_) => amount * 0.015
case BankTransfer(_) => 0.5
case Cash => 0.0
def masked(p: Payment): String = p match
case Card(n) => "card **** " + n.takeRight(4)
case BankTransfer(i) => s"transfer ${i.take(4)}…"
case Cash => "cash"
@main def run(): Unit =
val payments = List(Card("4111222233334444"), BankTransfer("DE89370400440532013000"), Cash)
for p <- payments do
println(f"${masked(p)}%-24s fee ${fee(p, 200)}%.2f")card **** 4444 fee 3.00
transfer DE89… fee 0.50
cash fee 0.00
case object is a singleton with the same benefits (nice toString, pattern matching) for alternatives that carry no data. In Scala 3 you can often express the same idea even more compactly with an enum (see Enums).
Case classes as map keys and in sets
Because equality is based on values, case classes work naturally as keys:
case class Cell(row: Int, col: Int)
@main def run(): Unit =
val board = Map(Cell(0, 0) -> "X", Cell(1, 1) -> "O")
println(board(Cell(1, 1)))
println(board.contains(Cell(2, 2)))
val visited = Set(Cell(0, 0), Cell(0, 0), Cell(0, 1))
println(visited.size)O
false
2
Tip: Keep case classes small and immutable. Avoid
varfields in case classes — mutating a value that is used as a map key or set element leads to very confusing bugs.
Test yourself
What does Point(1, 2) == Point(1, 2) return for case class Point(x: Int, y: Int)?
false, they are different objectstrue, case classes compare by value- A compile error
- It depends on
hashCode
How do you get a version of p with only y changed?
p.y = 5p.copy(y = 5)p.update(y = 5)new Point(p.x, 5).copy()
Why mark a trait sealed when modelling alternatives?
- To make it faster
- So all subtypes must be in the same file and the compiler can check matches for exhaustiveness
- To prevent pattern matching
- To make its fields private