Sealed Classes
Viewing old version ebd3983f086cb92bea6fe3a8d3f5eec1e730dcac; View Current
The Gist
Sealed Classes gives a really, really short overview, with no real code explaining sealed classes.
My Interpretation
Suppose we implemented our CaseClasses(case-classes-based) logger as such:
Notice that in our log method, we forgot the case for BothMessage. Scala will happily compile this code, but we’ll get a MatchError at runtime. If we add the keyword sealed to our abstract base class:
we will get a compile error that the match is not exhaustive. By sealing the class, Scala will not let any other subclasses of LogMessage be created outside this source file. Consequently, Scala can use this fact to check that our match statements are exhaustive.
Note that we could freely subclass any of LogMessage’s subclasses, since this doesn’t add new cases we need to handle.
My Thoughts on this Feature
Why Java doesn’t do this with enumerations is beyond me. Very useful for catching dumb coding mistakes and also a nice keyword to describe our set of types. This is where static typing really helps us out.
Last Updated 08/01/2009 at 02:53:26 PM by davec
blog comments powered by Disqus
All Content by David Copeland is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.