What are the differences between final class and sealed class in Scala?

user1187135 picture user1187135 · Aug 25, 2015 · Viewed 17.7k times · Source

There are two types of modifiers in Scala: final and sealed

What are the differences between them? When should you use one over the other?

Answer

dcastro picture dcastro · Aug 25, 2015

A final class cannot be extended, period.

A sealed trait can only be extended in the same source file as it's declared. This is useful for creating ADTs (algebraic data types). An ADT is defined by the sum of its derived types.

E.g.:

  • An Option[A] is defined by Some[A] + None.
  • A List[A] is defined by :: + Nil.

sealed trait Option[+A]

final case class Some[+A] extends Option[A]
object None extends Option[Nothing]

Because Option[A] is sealed, it cannot be extended by other developers - doing so would alter its meaning.

Some[A] is final because it cannot be extended, period.


As an added bonus, if a trait is sealed, the compiler can warn you if your pattern matches are not exhaustive enough because it knows that Option is limited to Some and None.

opt match {
    case Some(a) => "hello"
}

Warning: match may not be exhaustive. It would fail on the following input: None