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
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.
There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.