Instanceof Type Pattern Binding

Bind matched values directly with instanceof type patterns: the variable is in scope in the same condition and flows through null-safe checks.

JavaData Integrity

Code

snippet
import java.util.List;

public class ShapeDescriber {

    sealed interface Shape permits Circle, Rectangle, Group {}
    record Circle(double radius) implements Shape {}
    record Rectangle(double width, double height) implements Shape {}
    record Group(List<Shape> parts) implements Shape {}

    static String describe(Shape shape) {
        // instanceof 类型模式(type pattern):匹配成功即 binding 变量,
        // 绑定后的变量在作用域内直接用,不需要再强转
        if (shape instanceof Circle c) {
            return "circle r=" + c.radius();
        }
        // 绑定变量能用在同一个条件的后半段
        if (shape instanceof Rectangle r && r.width() == r.height()) {
            return "square " + r.width();
        }
        if (shape instanceof Rectangle r) {
            return "rect " + r.width() + "x" + r.height();
        }
        if (shape instanceof Group g) {
            return "group of " + g.parts().size();
        }
        return "unknown shape";
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(
                new Circle(2.5),
                new Rectangle(3, 3),
                new Rectangle(4, 2),
                new Group(List.of(new Circle(1), new Rectangle(2, 3))));
        for (Shape shape : shapes) {
            System.out.println(describe(shape));
        }
    }
}

How it works

Instanceof Type Pattern Binding is built around the classes ShapeDescriber, Shape, Circle and Rectangle and the functions describe and main.

Repetition is confined to for (Shape shape : shapes) — the rest of the file is straight-line.

Applying it

Entry signature: static String describe(Shape shape)

The sequence describe lives in main; running the file triggers it.

Statements that matter

if (shape instanceof Rectangle r && r.width() == r.height()) {
    return "square " + r.width();
}
return "rect " + r.width() + "x" + r.height();
return "group of " + g.parts().size();

Interactive Tools for This Topic

FAQ

How do you run Instanceof Type Pattern Binding?
Direct execution is enough; the script has no external requirements.