Records Equality And Pattern Switch

Get value equality for free with records and dispatch on their shape with pattern-matching switch — no getters or equals boilerplate.

JavaData Integrity

Code

snippet
public class ShapeMetrics {

    sealed interface Shape permits Circle, Rect {}

    record Circle(double radius) implements Shape {}
    record Rect(double w, double h) implements Shape {}

    static double area(Shape shape) {
        // record 模式匹配:解构与分派一体
        return switch (shape) {
            case Circle(double r) -> Math.PI * r * r;
            case Rect(double w, double h) -> w * h;
        };
    }

    public static void main(String[] args) {
        var circle = new Circle(2);
        var rect = new Rect(3, 4);

        // record 自带值相等:字段相同即相等
        System.out.println(new Circle(2).equals(circle));
        System.out.println("circle area = " + area(circle));
        System.out.println("rect area = " + area(rect));
    }
}

Inside the snippet

Records Equality And Pattern Switch reduces to the classes ShapeMetrics, Shape, Circle and Rect and the functions area and main.

Using it

The primary signature is static double area(Shape shape)

The demo output is labeled (circle area =, rect area =), so every printed line maps back to its originating operation.

The entry point wires area together — run it once and the whole demo flows.

Key statements

return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) -> w * h;
};

Interactive Tools for This Topic

FAQ

What does Records Equality And Pattern Switch print when run?
No setup needed: run the file and look for labeled lines like `circle area =`, `rect area =` in the output.