Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Case Classes and Pattern Matching

Scala Case Classes

Learn Scala 3 case classes: automatic equals, toString, copy and apply, immutable modeling, case objects, and how they compare with Java records.

Most programs spend their time moving small bundles of data around: a point, an order line, a user, a message. In many languages each bundle needs a class with a constructor, getters, equals, hashCode and toString. In Scala you write one line and the compiler produces all of it. That line starts with the word case.

A case class is an ordinary class that the compiler decorates with the members you almost always want for plain data. Case classes are also the foundation for pattern matching, which the next lessons build on, so it is worth knowing exactly what you get.

Declaring a case class

SCALA
case class Point(x: Int, y: Int)

val p = Point(3, 4)
println(p)          // Point(3,4)
println(p.x)        // 3

Three things happen here that would not for a plain class:

  • The constructor parameters become public val fields. You can read p.x without writing val yourself.
  • You create instances without new. The compiler adds a companion object with an apply method, so Point(3, 4) is really Point.apply(3, 4).
  • toString prints the class name followed by the fields, which makes debugging output readable.

What the compiler adds

apply Create instances without new.
equals and hashCode Compared by content, not identity.
toString Readable output like Point(3,4).
copy Make a changed duplicate.
1 / 2

Equality by value

In Java, two objects are equal only if the class overrides equals. Case classes do it for you: two instances are equal when they are the same class and all their fields are equal.

SCALA
case class Point(x: Int, y: Int)

val a = Point(1, 2)
val b = Point(1, 2)

println(a == b)         // true  (compared by content)
println(a eq b)         // false (two different objects)
println(a.hashCode == b.hashCode)  // true

Because hashCode is consistent with equals, case classes work correctly as keys in a Map and as elements of a Set:

SCALA
val visited = Set(Point(0, 0), Point(0, 0), Point(1, 1))
println(visited.size)   // 2

In Scala, == calls equals (and handles null safely). The operator eq checks reference identity, and you almost never need it.

Immutability and copy

Case class parameters are val by default, so an instance cannot change after it is created. Immutable data is easier to reason about, safe to share between threads and safe to use as a map key. When you need a changed version, use copy, which takes the same parameter names as the constructor and lets you override just the ones you name:

SCALA
case class User(name: String, age: Int, active: Boolean = true)

val ann = User("Ann", 30)
val older = ann.copy(age = 31)
val inactive = ann.copy(active = false)

println(ann)       // User(Ann,30,true)
println(older)     // User(Ann,31,true)
println(inactive)  // User(Ann,30,false)

The original ann is untouched. Notice also the default argument active: Boolean = true. Case classes support defaults and named arguments like any other method, so User("Bo", 25) and User(name = "Bo", age = 25, active = false) are both valid.

You can write var parameters in a case class (case class Counter(var n: Int)), but it throws away the main benefits. Avoid it unless you have a strong reason.

copy makes a shallow copy. If a field holds a mutable object such as an ArrayBuffer, the copy shares that same object. Prefer immutable collections in case classes and the problem disappears.

Taking a case class apart

Because the compiler generates unapply, you can deconstruct a case class in a val definition or a match:

SCALA
case class Point(x: Int, y: Int)

val Point(px, py) = Point(5, 8)
println(px + py)    // 13

def describe(p: Point): String = p match
  case Point(0, 0) => "origin"
  case Point(x, 0) => s"on the x axis at $x"
  case Point(_, y) => s"somewhere with y = $y"

You will see much more of this in Pattern Matching Basics. Case classes also extend Product, so p.productArity returns the number of fields, p.productElement(0) returns the first, and p.productIterator walks them all.

Case classes with methods and companions

A case class is still a full class. You can add methods, extra constructors and a companion object:

SCALA
case class Money(cents: Long):
  def +(other: Money): Money = Money(cents + other.cents)
  def dollars: String = f"${cents / 100.0}%.2f"

object Money:
  val zero: Money = Money(0)
  def fromDollars(d: Double): Money = Money(math.round(d * 100))

val total = Money.fromDollars(2.5) + Money.fromDollars(1.25)
println(total.dollars)   // 3.75

If you write your own companion object, the compiler still adds apply, unapply and friends to it. You can also override a generated method by writing your own, for example a custom toString.

Case objects

A class with no parameters has no data to compare, so the Scala way to model a single fixed value is a case object. It is a singleton with a readable toString and a sensible equals:

SCALA
case object Empty
println(Empty)     // Empty

Case objects are most useful as the "no-data" members of a family of types, which is the subject of Enums and Sealed ADTs.

Equivalents in Java and Kotlin

The idea is shared across the JVM languages. Java has record, Kotlin has data class. The runnable examples below are Java and Kotlin, not Scala (our runner does not run Scala), but they show the same behavior you just read: value equality, readable toString, and a copy-with-change step.

Java Java record: the same idea (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin data class: copy and destructuring (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the output format differs: Scala prints User(Ann,30,true) with no spaces and no field names, Kotlin prints User(name=Ann, age=30, active=true), Java records print Point[x=1, y=2]. The concept is identical.

Common mistakes

  • Writing new Point(1, 2). It works, but is unnecessary noise. Use Point(1, 2).
  • Inheriting from a case class. Extending one case class with another is forbidden because equality would become confusing. Put shared behavior in a trait or a sealed hierarchy instead.
  • Putting a mutable collection in a case class and assuming copy isolates it.
  • Comparing with eq when you meant ==.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given case class P(x: Int), what does P(1) == P(1) return?

    The compiler generates equals so that two instances of the same case class with equal fields are equal.
  2. 2. How do you create a changed duplicate of a case class instance?

    copy takes the constructor's parameter names as named arguments and returns a new instance.
  3. 3. Why can you write Point(1, 2) without new?

    The generated companion apply method calls the constructor. (Scala 3 also allows omitting new for ordinary classes through creator applications.)
  4. 4. What is the best way to model a fixed value with no data in a family of types?

    A case object is a singleton with a readable toString and proper equality.

Summary

  • A case class automatically gets apply, unapply, equals, hashCode, toString, copy and Product support.
  • Parameters are public immutable vals; instances are compared by content.
  • copy(field = value) creates a modified shallow copy; defaults and named arguments work as usual.
  • case object models a data-free singleton.
  • Java records and Kotlin data classes follow the same idea with different syntax.

Next: Pattern Matching Basics