Lesson contents

Scala — Sealed traits and pattern matching

Represent alternatives with a sealed trait and use pattern matching to handle their distinct data.

A simple example

Match a sealed type

  1. Start with Switch is On
  2. Do this Match On or Off
  3. Result 1
The two cases cover both possible values of Switch. The On case returns 1.
Lesson.scala
object Lesson extends App {
    sealed trait Switch
    case object On extends Switch
    case object Off extends Switch
    val state: Switch = On
    println(state match {
        case On => 1
        case Off => 0
    })
}
Output
1
Advertisements

Model a finite set of delivery states

A sealed trait restricts direct subclasses to the same source file. The match handles each declared variant and extracts the tracking number only from Sent.

Waiting parcel: No tracking yet. Sent parcel: Carries A17. Tracking display: A17.
Display the right delivery status

A parcel waiting at the desk has no tracking ID yet. A sent parcel carries the ID A17. Matching the delivery state lets the screen show the ID only for a parcel that has shipped.

Run the example

Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  sealed trait Delivery
  case class Sent(tracking: String) extends Delivery
  case object Waiting extends Delivery

  def label(item: Delivery): String = item match {
    case Sent(number) => "tracking " + number
    case Waiting => "waiting"
  }

  def main(args: Array[String]): Unit = {
    List(Waiting, Sent("A17")).foreach(item => println(label(item)))
  }
}
Output
waiting
tracking A17

Waiting carries no tracking data. Sent carries A17, which the matching case binds to a local name and formats as tracking A17.

Try it yourself

Add a Cancelled case object. What should change?

Check your answer

Add a matching case to label. The compiler can warn if a match on a sealed hierarchy leaves a known alternative unhandled.

Tour of Scala

Related tags

  • Scala
  • sealed traits
  • pattern matching
  • algebraic data types