What is the difference between sealed abstract and abstract Scala class?
+9
A:
The difference is that all subclasses of a sealed class (whether it's abstract or not) must be in the same file as the sealed class.
sepp2k
2010-06-13 15:34:16
Something not so obvious (at least it was not for me :-)) is that "grand children" of the sealed class can be in other files too:Given sealed class A; B extends A; C extends B. B must be in the same file as A, but C can leave in the same or in another.
Sandor Murakozi
2010-06-14 06:49:34
+7
A:
As answered, all subclasses of a sealed class (abstract or not) must be in the same file. A practical consequence of this is that the compiler can warn if the pattern match is incomplete. For instance:
sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[T](value: T) extends Tree
case object Empty extends Tree
def dps(t: Tree): Unit = t match {
case Node(left, right) => dps(left); dps(right)
case Leaf(x) => println("Leaf "+x)
// case Empty => println("Empty") // Compiler warns here
}
If the Tree
is sealed
, then the compiler warns unless that last line is uncommented.
Daniel
2010-06-13 19:33:14