[go: up one dir, main page]
More Web Proxy on the site http://driver.im/

This page is no longer maintained — Please continue to the home page at www.scala-lang.org

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 MatchErrorbeing 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.

 

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland