← 中文资源

简体中文版本

模式匹配 switch 密封类型

用 switch 模式匹配密封类型,实现穷尽处理。

阅读英文原文

示例说明

用 switch 模式匹配密封类型,实现穷尽处理。本示例属于数据完整性场景,提供可直接复制使用的java代码片段,附带边界条件与使用注意事项。

技术要点

  • sealed interface 限制子类型
  • permits 列出允许的子类
  • switch 模式匹配穷尽所有分支

代码解读

上述代码实现了模式匹配 switch 密封类型的核心逻辑。用 switch 模式匹配密封类型,实现穷尽处理。代码中包含输入校验、核心算法和结果返回三个部分。关键在于正确处理边界情况,例如空输入、非法参数和并发场景。sealed interface 限制子类型,permits 列出允许的子类。这些设计确保代码在生产环境中的健壮性。

使用建议

在实际项目中使用本示例时,建议先理解模式匹配 switch 密封类型的适用场景与限制条件。switch 模式匹配穷尽所有分支。根据具体业务需求调整参数配置,并编写单元测试覆盖正常路径与边界情况。本代码片段可直接集成到现有项目中,或作为参考实现自行扩展。

代码示例

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