JEP 361: Switch Expressions
Java 各版本和特性(Java Versions and Features)
selector expression which must be of type char, byte, short, int, Character, Byte, Short, Integer, String, or an enum
选择语句,支持char, byte, short, int, Character, Byte, Short, Integer, String, or an enum这类类型的选择语句。
新的switch语法,例:
public class SwitchExpressions
{
public static void main(String[] argv)
{
System.out.println(isWeekDayV1_1(Day.MON)); //true
System.out.println(isWeekDayV1_2(Day.MON)); //true
System.out.println(isWeekDayV2(Day.MON)); //true
}
//1 - Return value directly
enum Day {
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static Boolean isWeekDayV1_1 (Day day)
{
Boolean result = switch(day) {
case MON, TUE, WED, THUR, FRI -> true;
case SAT, SUN -> false;
};
return result;
}
public static Boolean isWeekDayV1_2 (Day day)
{
Boolean result = switch(day) {
case MON, TUE, WED, THUR, FRI : yield true;
case SAT, SUN : yield false;
};
return result;
}
//2 - Multiple statements in case block
public static Boolean isWeekDayV2 (Day day)
{
Boolean result = switch(day) {
case MON, TUE, WED, THUR, FRI ->
{
System.out.println("It is WeekDay");
yield true;
}
case SAT, SUN ->
{
System.out.println("It is Weekend");
yield false;
}
};
return result;
}
}
以前需要写如下代码
public enum Day { SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }
// ...
int numLetters = 0;
Day day = Day.WEDNESDAY;
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("Invalid day: " + day);
}
System.out.println(numLetters);
现在减少很多代码
Day day = Day.WEDNESDAY;
System.out.println(
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
default -> throw new IllegalStateException("Invalid day: " + day);
}
);
结论:
- In Java 14, switch expressions are a standard feature. In Java 13 and Java 12, it was added as an preview feature.
- It has the support of multiple case labels and using keyword
yield
to return value in place of oldreturn
keyword. - It also support returning value via label rules (arrow operator similar to lambda).
- If we use arraw
(->)
operator, we can skipyield
keyword as shown in isWeekDayV1_1(). - If we use colon
(:)
operator, we need to useyield
keyword as shown in isWeekDayV1_2(). - In case of multiple statements, use curly braces along with
yield
keyword as shown in isWeekDayV2(). - In case of
enum
, we can skip the default case. If there is any missing value not handled in cases, compiler will complain. In all other expression types (int, strings etc), we must providedefault
case as well.如果选择类型是枚举,case 语句可以跳过defaut条件。但其它选择类型,必须要default条件