发布于 4年前

Java14新特性:Switch表达式

Java 14正式发布switch表达式特性。在之前的两个 Java 版本Java12,Java13,switch特性只是预览版。

新的switch表达式有助于避免一些bug,因为它的表达和组合方式更容易编写。

switch新的表达式有两个特点:

  • 支持箭头表达式返回。
  • 支持yied和return返回值。

Java 14之前switch语法:

switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}

Java 14 switch表达式

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

Java 14的switch表达式使用箭头表达时,不需要我们在每一个case后都加上break,减少我们出错的机会。

Java14之前switch语法返回值

int numLetters;
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        numLetters = 6;
        break;
    case TUESDAY:
        numLetters = 7;
        break;
    case THURSDAY:
    case SATURDAY:
        numLetters = 8;
        break;
    case WEDNESDAY:
        numLetters = 9;
        break;
    default:
        throw new IllegalStateException("Wat: " + day);
}

它不支持返回值,需要通过一个中间变量来返回。

Java14 switch表达式返回值

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;
};

Java 14 Switch表达式使用yield返回值

int j = switch (day) {
    case MONDAY  -> 0;
    case TUESDAY -> 1;
    default      -> {
        int d = day.toString().length();
        int result = f(d);
        yield result;
    }
};
©2020 edoou.com   京ICP备16001874号-3