← 中文资源

简体中文版本

instanceof 类型模式绑定

instanceof 类型模式把匹配结果直接绑定成变量,同一条件的后半段就能使用;判否后类型自动收窄,配合密封接口把类型分派写得完整紧凑。

阅读英文原文

实现说明

除了类 ShapeDescriber、Shape、Circle、Rectangle和函数 describe、main,文件里再无其他定义。 在这里做循环的是 for (Shape shape : shapes)。

使用要点

  • 运行整个文件:main 会依次驱动 describe。

常见问题

「instanceof 类型模式绑定」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

入口签名:static String describe(Shape shape)

核心语句

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

代码示例

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