67

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?

2 Answers 2

107

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

2
  • 16
    Technically speaking sealed templates can be extended in the same compilation unit, not the same file. The fact that the Scala compiler's compilation unit equals a file is an implementation detail. There could be other compilers which use, for example, a database to store source artifacts instead of the filesystem. Aug 25, 2015 at 11:49
  • 2
    @JörgWMittag Thanks for the addendum, I wasn't aware of that distinction.
    – dcastro
    Aug 25, 2015 at 11:54
9

sealed classes (or traits) can still be inherited in the same source file (where final classes can't be inherited at all).

Use sealed when you want to restrict the number of subclasses of a base class (see "Algebraic Data Type").

As one of the very practical benefits of such a restriction the compiler can now warn you about non-exaustive pattern matches:

sealed trait Duo
case class One(i:Int) extends Duo
case class Two(i:Int, j:Int) extends Duo

def test(d:Duo) {
  match {
    case One(x) => println(x) // warning since you are not matching Two
  }
}
1
  • 3
    Technically speaking sealed templates can be extended in the same compilation unit, not the same file. The fact that the Scala compiler's compilation unit equals a file is an implementation detail. There could be other compilers which use, for example, a database to store source artifacts instead of the filesystem. Aug 25, 2015 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy