Case classes
A case class is a class declared for a value. The compiler adds the methods a value needs — equals, hashCode, toString, copy, the companion with apply and unapply — and the fields are vals, so an instance cannot change. It is the type this course reaches for first, and the reason is the list of methods nobody has to remember.
The methods the compiler writes
Point declares two fields and nothing else, and it already prints as Point(1,2), compares by value and makes a copy with one field changed. Segment is a case class built from two of them:
case_classes.scala
case class Point(x: Int, y: Int)
case class Segment(from: Point, to: Point):
def length: Double = math.hypot(to.x - from.x, to.y - from.y)
@main def case_classes(): Unit =
val a = Point(1, 2)
val b = Point(1, 2)
println(a)
println(a == b)
println(a eq b)
println(a.copy(y = 9))
val segment = Segment(Point(0, 0), Point(3, 4))
println(segment)
println(segment.length)
println(segment.to.y)
scala-cli run --server=false case_classes.scala
Point(1,2)
true
false
Point(1,9)
Segment(Point(0,0),Point(3,4))
5.0
4
a == b is true and a eq b is false: the compiler wrote equals, so two points with the same coordinates are one value. a.copy(y = 9) is a new instance, not a change, and the field of a case class cannot be reassigned at all. The call Point(1, 2) works without new because the companion object has the apply the compiler wrote.
copy, defaults and a nested value
A default value in the constructor keeps a field out of most call sites, and copy takes a field by name, which is where the named arguments of a method pay off. A case class can hold a list and another case class without any extra code:
events.scala
case class Event(name: String, day: Int, tags: List[String] = Nil)
@main def events(): Unit =
val first = Event("Scala", 1, List("talk"))
val second = Event("Scala", 1, List("talk"))
println(first == second)
println(first.copy(day = 2))
println(first.tags == second.tags)
val renamed = first.copy(name = "Kotlin")
println(renamed)
println(List(first, renamed).map(_.name).mkString(", "))
val bare = Event("Scala", 1)
println(bare)
println(bare.tags.isEmpty)
scala-cli run --server=false events.scala
true
Event(Scala,2,List(talk))
true
Event(Kotlin,1,List(talk))
Scala, Kotlin
Event(Scala,1,List())
true
first == second compares the fields deeply, the List of tags included. Event("Scala", 1) uses the default, and copy(name = "Kotlin") changes one field and keeps the rest, which is how a program describes a change without a setter. Every case class is also a product: productIterator walks its fields in declaration order.
Related
- Tuples: the unnamed version of the same idea.
- Equality: what the generated equals has to satisfy.
- Objects and companions: the apply and unapply behind a case class.
- Pattern matching: the case Point(x, y) the companion's unapply makes possible.
Article author: Arthur Isaev