Pattern Matching Switch Sealed
Use pattern matching with switch on sealed types for exhaustive handling.
Code
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();
};
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.