Does Java sealed classes enable something like an exhaustive pattern matching? (A form of pattern matching that will fail at compile time if you add a new class that extends the sealed class)
sealed interface BinaryTree {
record Leaf(int value) implements BinaryTree {}
record Node(BinaryTree lhs,
BinaryTree rhs,
int value) implements BinaryTree {}
}
public class Hello {
static int sum(BinaryTree tree) {
return switch (tree) {
case BinaryTree.Leaf(var value) -> value;
case BinaryTree.Node(var lhs, var rhs, var value) -> sum(lhs) + value + sum(rhs);
};
}
public static void main(String... args) {
var tree = new BinaryTree.Node(
new BinaryTree.Leaf(1),
new BinaryTree.Node(
new BinaryTree.Leaf(2),
new BinaryTree.Leaf(3),
4),
5);
System.out.println(tree);
System.out.println("Sum: " + sum(tree));
}
}
If you added a new subtype to BinaryTree you would need to fix the switch.
EDIT: I didn't handle the `null` case above... so it would be a NullPointerException if someone passed null... apparently, Java decided to make handling `null` optional. More information: https://www.baeldung.com/java-lts-21-new-features
It absolutely does. Here is a (modified) snippet of my Java code from yesterday.
final boolean hasUncollectedSecret =
switch (each)
{
case Wall() -> false;
case Goal() -> false;
case Player p -> false;
case BasicCell(Underneath(_, var collectible), _)
->
switch (collectible)
{
case NONE, KEY -> false;
case SECRET -> true;
};
case Lock() -> false;
};
Example:
If you added a new subtype to BinaryTree you would need to fix the switch.EDIT: I didn't handle the `null` case above... so it would be a NullPointerException if someone passed null... apparently, Java decided to make handling `null` optional. More information: https://www.baeldung.com/java-lts-21-new-features