Published on The Scala Programming Language (http://www.scala-lang.org)


By admin
Created 2008-07-05, 21:10

A Tour of Scala: Sealed Classes

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 [1]being raised at run-time.

When applied to the selector of a match expression, the @unchecked [2] 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 [2] annotation, a Scala compiler could infer that the pattern match is non-exhaustive, and could produce awarning because Option is a sealed class.

 


Source URL (retrieved on 2013-05-22, 09:53): http://www.scala-lang.org/node/123

Links:
[1] http://www.scala-lang.org/sites/default/files/linuxsoft_archives/docu/files/api/scala/MatchError.html
[2] http://www.scala-lang.org/sites/default/files/linuxsoft_archives/docu/files/api/scala/unchecked.html