Sealed Classes
A sealed class or trait has a fixed list of children that must all live in one file. It is like a closed guest list, so Scala can check you handled every guest.
In this page:
Syntax
sealed trait TraitName
case class First(field: Type) extends TraitName
case class Second(field: Type) extends TraitName
case object Third extends TraitName
Sealed Classes
Marking a class or trait sealed restricts all its direct subtypes to being defined in the same source file, letting the compiler check that a match expression covers every possible case exhaustively.
This is especially powerful combined with case classes to model a fixed, closed set of variants (like a simple enum-style hierarchy). The compiler warns if a match on a sealed hierarchy misses a case.
Note:
sealed combined with case classes gives you compiler-checked exhaustiveness warnings on match expressions -- a very common, powerful Scala pattern.
Example: Sealed Classes
sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Square(side: Double) extends Shape
object Main extends App {
def area(shape: Shape): Double = shape match {
case Circle(r) => Math.PI * r * r
case Square(s) => s * s
}
println(area(Circle(2)))
println(area(Square(3)))
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Defining a subclass of a
sealedtrait in another file, which does not compile. - Forgetting to add a new subclass to a
match, so the compiler gives a warning about a non-exhaustive match that is ignored. - Adding a
case _default in thematch, which hides the warning that would show a missing subtype.
Chapter Summary
- Inheritance lets a class extend another and override methods.
- Abstract classes and traits define shared behavior, and traits can be mixed in.
- Sealed classes limit the set of subclasses.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: