在Java中用类似Lambda的语法将开关作为一个表达式

从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 作为一个表达式返回一个单一的整数值。同样的语法可以用在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

参考文献

猜你喜欢

转载自juejin.im/post/7125710803751141389