Re:Algebraic Data Types for C99
by nextaccountic on Thursday May 09, 2024 @12:24PM
(#40309834)
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)
[ Parent
| on HN ]
Yes, since Java 21.
Example:
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
Re:Algebraic Data Types for C99
by nextaccountic on Thursday May 09, 2024 @01:06PM
(#40310332)
Okay that's better than I expected!
Re:Algebraic Data Types for C99
by davidalayachew on Thursday May 09, 2024 @01:08PM
(#40310348)
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;
};
Re:Algebraic Data Types for C99
by thewakalix on Thursday May 09, 2024 @12:31PM
(#40309914)
> The intent is to introduce a more-advanced construction called pattern matching in a later release.
You read that in a blog post from 2019.
Java has had comprehensive pattern matching since Java 21, like one year ago (current Java version is 22).
I posted an answer to the same parent comment with the C example written in Java...
You can read more about it here: https://www.baeldung.com/java-lts-21-new-features