Benefits of sealed traits in Scala (like enum in Java)

As a quick note about traits in Scala, this StackOverflow page makes a few good points about sealed traits:

  • sealed traits can only be extended in the same file
  • this lets the compiler easily know all possible subtypes
  • example: the compiler can emit warnings if a match/case expression is not exhaustive
  • use sealed traits when the number of possibly subtypes is finite and known in advance
  • they can be a way of creating something like an enum in Java

For functional programming sealed traits also offer one really big advantage:

  • they help you define algebraic data types, or ADTs

Sealed trait examples

Examples of things that can be sealed traits are days in the week, months in a year, and the suits in a deck of cards.

The first answer from that SO page shows a simple example of how to write a sealed trait:

sealed trait Answer
case object Yes extends Answer
case object No extends Answer

This article on noelwelsh.com about algebraic data types and sealed traits is also helpful.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.