Recall from Case Classes that we demonstrated pattern matching with our
Shapes hierarchy, which use case classes. We had a
case _ => ...
expression. It’s usually wise to have one. Otherwise, if someone defines a
new subtype of
Shape and passes it to this
match statement, a runtime
scala.MatchError will be thrown, because the new shape
won’t match the shapes covered in the match statement. However, it’s not
always possible to define reasonable behavior for the default
There is an alternative
solution if you know that the case class hierarchy is unlikely to change
and you can define the whole hierarchy in one file.
In this situation, you can add the
sealed keyword to
the declaration of the common base class. When sealed, the compiler knows
all the possible classes that could appear in the
expression, because all of them must be defined in the same source file.
So, if you cover all those classes in the
expressions (either explicitly or through shared parent classes), then you
can safely eliminate the default
Here is an example using the HTTP 1.1 methods (see [HTTP1.1]), which are not likely to change very often, so we declare a “sealed” set of case classes for them: