Scala Case Classes
A case class is a class built for holding simple values. Scala adds readable printing, value equality, and copying to a case class for free.
A case class prints readably
The Point case class holds two numbers. Printing the value shows its name and both fields.
case class Point(x: Int, y: Int)
@main def main(): Unit =
val p = Point(1,2)
println(p)
println(p.x)
println(p.y)Case class equality compares values
Two plain class values with the same fields are not equal here. Two case class values with the same fields are equal.
class PlainPoint(val x: Int, val y: Int)
case class Point(x: Int, y: Int)
@main def main(): Unit =
val a = PlainPoint(1,2)
val b = PlainPoint(1,2)
println(a == b)
val p = Point(1,2)
val q = Point(1,2)
println(p == q)
val r = Point(1, 3)
println(p == r)Copy changes one field
The copy call names the field to change. The new value shows the change, and the first value stays the same.
case class Point(x: Int, y: Int)
@main def main(): Unit =
val p = Point(1,2)
val q = p.copy(y = 5)
println(q)
println(p)Example
case class City(name: String, people: Int)
@main def main(): Unit =
val first = City("Oslo", 700)
val second = first.copy(people = 750)
println(first)
println(second)
println(first == second)
println(second.name)Key points
- Case class: a class marked with the words case class, made for holding values.
- Printing: printing a case class value shows the class name and its field values in one readable line.
- Equality: the == sign on two case class values compares their field values.
- Plain class: two separate plain class values are not ==, even when their fields are the same.
- Copy: the copy method makes a new value with the named fields changed and the rest kept the same.
- Fields: the fields of a case class value are read by name with a dot, like p.x.
In this example, the City case class holds a name and a count of people. The copy call builds a second city with the count changed to 750, while the first city keeps 700. The two values are not equal because their counts differ, and the last line reads the name field of the copy.
Note
copy leaves the original value unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does println(Point(1,2) == Point(1,2)) print for a case class Point?