Hacker News new | ask | show | jobs
by cies 523 days ago
Just having sum types is not enough: you need some level of type safety and exhaustivity checking in match/switch statements to truly benefit from them.

Go does not. Java did not (maybe now with sealed types and exhausitvity checks on switch statement, but not sure if they've already landed).

1 comments

Java does have exhaustiveness checking on switch expressions over sealed types in the release JDK, but not switch statements (due to the requirement for backwards compatibility). I'll often find myself writing var _ = <some switch>; to get around this, a very Java idiom if ever there was one, heh
Java does have exhaustiveness checking on switch statements for sealed types, but not enums (for backward compatibility), which is probably what you're using.

Try this:

    sealed interface Shape permits Circle, Rectangle { }
    record Circle(double radius) implements Shape { }
    record Rectangle(double length, double width) implements Shape { }

    void test() {
        Shape shape = new Circle(5);
        switch (shape) {
            case Circle _ -> System.out.println("Circle");
            case Rectangle _ -> System.out.println("Rectangle"); // Comment out this line to get an error.
        }
    }