Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Case Classes and Pattern Matching

Scala Enums, Sealed Traits and ADTs

Model data precisely with Scala 3 enums, sealed traits and algebraic data types, and let the compiler check that every case is handled in a match.

How do you represent "a payment is either a card, a bank transfer or cash"? A string field with magic values is fragile: a typo compiles fine. A class hierarchy that anyone can extend means you can never be sure you handled every kind. Scala solves this with algebraic data types (ADTs): a closed set of alternatives that the compiler knows completely.

This lesson shows the two tools for it: enum (Scala 3) and sealed trait. Both give you exhaustiveness checking, which turns "I forgot a case" from a production bug into a compile warning.

Simple enums

For a fixed list of constants, use enum:

SCALA
enum Color:
  case Red, Green, Blue

val c = Color.Green
println(c)                  // Green
println(c.ordinal)          // 1
println(Color.valueOf("Blue"))  // Blue
println(Color.values.toList)    // List(Red, Green, Blue)

Every enum gets values, valueOf and ordinal. You can add fields and methods, much like Java enums:

SCALA
enum Planet(val massKg: Double, val radiusM: Double):
  case Earth extends Planet(5.97e24, 6.37e6)
  case Mars  extends Planet(6.42e23, 3.39e6)

  def surfaceGravity: Double = 6.67e-11 * massKg / (radiusM * radiusM)

Enums with parameters: ADTs

Scala enums can carry data per case, which makes them full algebraic data types:

SCALA
enum Shape:
  case Circle(radius: Double)
  case Rectangle(width: Double, height: Double)
  case Point

import Shape.*

def area(s: Shape): Double = s match
  case Circle(r) => math.Pi * r * r
  case Rectangle(w, h) => w * h
  case Point => 0.0

Each parameterized case behaves like a case class (equality by value, copy, pattern matching). case Point without parameters is a singleton. The import Shape.* brings the cases into scope so you can write Circle(1.0) instead of Shape.Circle(1.0).

Because Shape is closed, the compiler knows that Circle, Rectangle and Point are the only possibilities. Delete the Point line from area and you get a warning: match may not be exhaustive. It would fail on: Shape.Point.

Why closed hierarchies help

Closed set Only the cases you declare exist.
Exhaustive match Compiler warns about a missing case.
Safe refactoring Add a case and see every place to update.
1 / 2

Sealed traits

A sealed trait (or abstract class) can only be extended in the same file. That is how the compiler gets its complete list of subtypes.

SCALA
sealed trait PaymentMethod
case class Card(number: String, holder: String) extends PaymentMethod
case class BankTransfer(iban: String) extends PaymentMethod
case object Cash extends PaymentMethod

def fee(p: PaymentMethod): Double = p match
  case Card(_, _) => 0.029
  case BankTransfer(_) => 0.005
  case Cash => 0.0

This is the classic Scala 2 style and is still used a lot. Prefer it over enum when cases are unrelated classes you also want to reuse elsewhere, or when you need to inherit from other traits.

Sealed is not the same as final: you can subclass within the file, and each subclass decides whether it is final, sealed or open.

A recursive ADT: expressions

ADTs really come alive when they refer to themselves. Here is a tiny arithmetic language:

SCALA
enum Expr:
  case Num(value: Double)
  case Add(left: Expr, right: Expr)
  case Mul(left: Expr, right: Expr)
  case Neg(inner: Expr)

import Expr.*

def eval(e: Expr): Double = e match
  case Num(v) => v
  case Add(l, r) => eval(l) + eval(r)
  case Mul(l, r) => eval(l) * eval(r)
  case Neg(x) => -eval(x)

val formula = Add(Num(2), Mul(Num(3), Neg(Num(4))))
println(eval(formula))   // -10.0

One function per operation, each exhaustive. This "data plus functions over it" style is the heart of functional design, and you will use it in the expression evaluator project.

flowchart TD
    A["Add"] --> B["Num(2)"]
    A --> C["Mul"]
    C --> D["Num(3)"]
    C --> E["Neg"]
    E --> F["Num(4)"]

The tree for 2 + 3 * (-4). A match walks it recursively.

Generic ADTs

ADTs can have type parameters. Scala's own Option and List are ADTs, and you can write your own:

SCALA
enum Result[+E, +A]:
  case Ok(value: A)
  case Fail(error: E)

def parseAge(s: String): Result[String, Int] =
  s.toIntOption match
    case Some(n) if n >= 0 => Result.Ok(n)
    case Some(_) => Result.Fail("negative age")
    case None => Result.Fail(s"not a number: $s")

The + marks the parameters as covariant (a Result[String, Int] can be used where a Result[Any, Any] is expected). Scala's standard Either[Left, Right] already does this job, see Option, Either and Try.

Enums vs. sealed traits at a glance

Need Use
A list of named constants enum
Alternatives carrying different data enum with parameterized cases
Alternatives that extend other traits or are reused as types sealed trait + case classes
Java interop with a Java enum enum Color extends java.lang.Enum[Color]

The same idea in Java and Kotlin

Java 17+ has sealed interface with record cases, and switch over them is checked for exhaustiveness without a default. Kotlin has sealed interface and when. Both examples below are not Scala but mirror the Expr ADT.

Java Java: sealed interface + records, exhaustive switch (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: enum and sealed class (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.

Common mistakes

  • Leaving a catch-all case _ in a match over an ADT. It silences the exhaustiveness warning, so a new case will slip through unhandled. Only use _ when you truly mean "everything else".
  • Defining sealed subclasses in another file. The compiler refuses; keep the whole family together.
  • Using strings or Ints as pseudo-enums. Typos then compile.
  • Ignoring warnings. Many teams turn on -Werror (or -Wconf) so that a non-exhaustive match breaks the build; see sbt and Project Setup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does sealed guarantee about a trait?

    Sealing restricts direct subtypes to the same source file, so the compiler knows every alternative and can check matches for exhaustiveness.
  2. 2. Which line is a valid parameterized enum case?

    Enum cases can take parameters like a case class constructor.
  3. 3. What does Color.values return for enum Color: case Red, Green, Blue?

    Every enum gets values (an Array), valueOf and ordinal for free.
  4. 4. Why is a final case _ in a match over a sealed type risky?

    With a wildcard every value is covered, so the compiler cannot tell you that a newly added case is unhandled.

Summary

  • Algebraic data types describe a closed set of alternatives, each possibly carrying data.
  • enum is the compact Scala 3 way; sealed trait plus case classes/objects works in all versions.
  • The compiler checks match expressions over sealed types for exhaustiveness.
  • ADTs can be recursive and generic, which is how expression trees, Option and Either are built.
  • Avoid a blanket case _ when you want the compiler's help.

Next: Advanced Patterns and Extractors