Pattern Matching Switch Sealed

Use pattern matching with switch on sealed types for exhaustive handling.

JavaData Integrity

Code

snippet
public sealed interface Shape permits Circle, Square, Rectangle {}
public record Circle(double radius) implements Shape {}
public record Square(double side) implements Shape {}
public record Rectangle(double w, double h) implements Shape {}

public class Area {
    public static double compute(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.radius() * c.radius();
            case Square sq -> sq.side() * sq.side();
            case Rectangle r -> r.w() * r.h();
        };
    }
}