Contents

Java 写出Rust 的match 代码

Contents

Java 写出Rust 的match 代码

在Java中,我们可以使用switch语句来实现类似于Rust中match的功能。下面是一个示例,展示了如何在Java中使用switch来模拟Rust的match语法。


public enum ServiceType {
    RESUME_COMMUNICATION(1, "复课沟通"),
    CLASS_PLANNING(2, "班级规划"),
    STUDENT_PLANNING(3, "学员规划"),
    STUDENT_INVENTORY(4, "学员盘点"),
    RENEWAL_INVENTORY_LOCK(5, "续报盘点锁定"),
    SATISFACTION_SURVEY(6, "满意度问卷");

    private final Integer code;
    private final String description;

    ServiceType(Integer code, String description) {
        this.code = code;
        this.description = description;
    }

    public Integer getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public static ServiceType fromCode(Integer code) {
        for (ServiceType type : values()) {
            if (type.code.equals(code)) {
                return type;
            }
        }
        throw new IllegalArgumentException("Unknown service type code: " + code);
    }

    // 模拟 Rust 的 match 表达式
    public <T> T match(
        java.util.function.Supplier<T> resumeCommunication,
        java.util.function.Supplier<T> classPlanning,
        java.util.function.Supplier<T> studentPlanning,
        java.util.function.Supplier<T> studentInventory,
        java.util.function.Supplier<T> renewalInventoryLock,
        java.util.function.Supplier<T> satisfactionSurvey
    ) {
        switch (this) {
            case RESUME_COMMUNICATION: return resumeCommunication.get();
            case CLASS_PLANNING: return classPlanning.get();
            case STUDENT_PLANNING: return studentPlanning.get();
            case STUDENT_INVENTORY: return studentInventory.get();
            case RENEWAL_INVENTORY_LOCK: return renewalInventoryLock.get();
            case SATISFACTION_SURVEY: return satisfactionSurvey.get();
            default: throw new IllegalStateException("Unexpected value: " + this);
        }
    }
}

使用示例:


// 基本用法
ServiceType type = ServiceType.fromCode(1);
System.out.println(type.getDescription()); // 输出: 复课沟通

// 模拟 Rust 的 match
String result = type.match(
    () -> "处理复课沟通",
    () -> "处理班级规划",
    () -> "处理学员规划",
    () -> "处理学员盘点",
    () -> "处理续报盘点锁定",
    () -> "处理满意度问卷"
);
System.out.println(result); // 输出: 处理复课沟通

Java 枚举虽然不如 Rust 的枚举灵活(不支持携带不同类型的数据),但这种方式已经能提供类型安全和模式匹配的基本功能。