← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 7 of 7

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:

  1. Sealed Classes
Syntax
scala
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

markup
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)))
}
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
  1. Defining a subclass of a sealed trait in another file, which does not compile.
  2. Forgetting to add a new subclass to a match, so the compiler gives a warning about a non-exhaustive match that is ignored.
  3. Adding a case _ default in the match, 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.