What is the difference between sealed abstract
and abstract
Scala class?
Asked
Active
Viewed 2.4k times
74

Michal Kordas
- 10,475
- 7
- 58
- 103

Łukasz Lew
- 48,526
- 41
- 139
- 208
2 Answers
94
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
- 363,768
- 54
- 674
- 675
-
38Something 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 Jun 14 '10 at 06:49
-
8@SandorMurakozi You must declare B as a sealed class as well, if you want to achieve that. Sealing only deals with direct inheritance. – natbusa Oct 10 '14 at 09:51
80
As answered, all directly inheriting 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.

Community
- 1
- 1

Daniel C. Sobral
- 295,120
- 86
- 501
- 681
-
1Why can't the compiler infer that pattern match is incomplete if there is no `sealed` keyword? – sasha.sochka Apr 08 '14 at 12:06
-
7@sasha.sochka Suppose I compile it and put it in a jar file, without the `sealed` keyword. It's all been compiled at that point, including the `match` statement. Now, another user grabs this jar and _extends `Tree`_. There's nothing preventing him from doing so, but, at that point, the `match` statement is no longer complete. Since he isn't compiling it, just using it from your jar, the compiler can't warn _him_. And since you did not know of it when you created the jar, it couldn't have warned you. – Daniel C. Sobral Apr 08 '14 at 17:32
-
@DanielCSobral, You wrote "but, at *that* point, the match statement is no longer complete". Isn't the match statement incomplete at *this* moment, when you compile the original code you posted (but without `sealed` keyword), before making a jar file? It looks like easy to infer, because even without new children (compiler doesn't know about them yet) there is no branch for `Empty`. And I'm talking about a warning for the person who creates a jar, not about a person who uses it. – sasha.sochka Apr 08 '14 at 17:39
-
1@sasha.sochka Well, I suppose it could warn that `Empty` is missing, but the point is that, even if you add `Empty`, it could still be incomplete, or not, depending on what happens at separate compilations. – Daniel C. Sobral Apr 08 '14 at 17:43
-