- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
A Tour of Scala: Sealed Classes
Created by admin on 2008-07-05.
Updated: 2008-07-21, 17:02
A sealed class may not be directly inherited, except if the inheriting template is defined in the same source file as the inherited class. However, subclasses of a sealed class can inherited anywhere.
Sealed classes are defined using the sealed
modifier.
If the selector of a pattern match is an instance of a sealed class, the compilation of pattern matching can emit warnings which diagnose that a given set of patterns is not exhaustive, i.e. that there is a possibility of a MatchError
being raised at run-time.
When applied to the selector of a match expression, the @unchecked
annotation suppresses any warnings about non-exhaustive pattern matches which would otherwise be emitted. For instance, no warnings would be produced for the method definition below.
def f(x: Option[Int]) = (x: @unchecked) match { case Some(y) => y }
Without the @unchecked
annotation, a Scala compiler could infer that the pattern match is non-exhaustive, and could produce awarning because Option
is a sealed class.