Hacker News new | ask | show | jobs
by nextaccountic 767 days ago
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)
3 comments

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

Okay that's better than I expected!
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;
               
       };
> 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