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
- Start with Switch is On
- Do this Match On or Off
- Result 1
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
})
}
1
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.
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
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)))
}
}
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.