在Java 14中使用类似Lambda的switch表达式 - codeleak


从Java 14开始,switch表达式具有额外的Lambda-like(case ... -> labels)语法,不仅可以用作语句,还可以用作计算为单个值的表达式。

类似Lambda的语法(case ... -> labels)
使用新的类似Lambda的语法,如果标签匹配,则仅执行箭头右侧的表达式或语句:

var result = switch (str) {
    case "A" -> 1;
    case
"B" -> 2;
    case
"C" -> 3;
    case
"D" -> 4;
    default -> throw new IllegalStateException(
"Unexpected value: " + str);
};

上面是switch作为返回单个整数值的表达式的示例,下面箭头右边是语句。

int result;
switch (str) {
    case "A" -> result = 1;
    case
"B" -> result = 2;
    case
"C" -> {
        result = 3;
        System.out.println(
"3!");
    }
    default -> {
        System.err.println(
"Unexpected value: " + str);
        result = -1;
    }
}

yield
case,yield可用于从中返回值:

var result = switch (str) {
    case "A" -> 1;
    case
"B" -> 2;
    case
"C" -> {
        System.out.println(
"3!");
        yield 3;
// return
    }
    default -> throw new IllegalStateException(
"Unexpected value: " + str);
};

每个Case的多个常量
也可以在case中使用以逗号分隔的多个常量,进一步简化了以下用法switch:

var result = switch (str) {
    case "A" -> 1;
    case
"B" -> 2;
    case
"C" -> 3;
    case
"D", "E", "F" -> 4;
    default -> 5;
};

最后的例子
为了演示新switch语法,我创建了这个小计算器:


double calculate(String operator, double x, double y) {
    return switch (operator) {
        case "+" -> x + y;
        case
"-" -> x - y;
        case
"*" -> x * y;
        case
"/" -> {
            if (y == 0) {
                throw new IllegalArgumentException(
"Can't divide by 0");
            }
            yield x / y;
        }
        default -> throw new IllegalArgumentException(
"Unknown operator '%s'".formatted(operator));
    };
}

源代码
可以在Github上找到本文的源代码:https : //github.com/kolorobot/java9-and-beyond