Scala - Sealed Class Hierarchies
In my previous article i had shared you regarding Option feature in Scala, in this article come lets discuss about design feature in Scala it uses.
A key point about Option is that there are really only two valid subtypes. Either we have a value, the Some case, or we don’t, the None case. There are no other subtypes of Option that would be valid. So, we would really like to prevent users from creating their own.
Scala has a keyword sealed for this purpose. Option is declared like this (eliding some details):
sealed abstract class Option[+A] ... { ... }
The sealed keyword tells the compiler that all subclasses must be declared in the same source file. Likewise Some and None are declared in the same file with Option in the Scala library. This technique effectively prevents additional subtypes of Option.
You can also declare a type final if you want to prevent users from subtyping it.