Pattern Matching Switch Sealed

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

JavaData Integrity

Code

javasnippet
14 lines
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();
        };
    }
}

Inside the snippet

The working surface is the classes Shape, Circle, Square and Rectangle and the function compute — everything else is wiring.

Putting it to use

The entry-point signature is public static double compute(Shape s)

Core lines

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();
};

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `compute` at load time.