350: Dynamic CDS Archives 351: ZGC: Uncommit Unused Memory 353: Reimplement the Legacy Socket API 354: Switch Expressions (Preview) 355: Text Blocks (Preview)
Among the above, today I would like to take a look at "Switch Expressions (Preview)".
Switch Expressions (Preview) --Is it Preview in JDK 12 or Preview in 13? Since it is --Preview, it seems that it cannot be used unless the --enable-preview option is given.
static void howMany(int k) {
switch (k) {
case 1 -> System.out.println("one");
case 2 -> System.out.println("two");
default -> System.out.println("many");
}
}
I used to use the conventional "case L:", but now I can use it like "case L->". However, if you write something like "case L->", there is no full through, so you don't have to write break.
howMany(1);
howMany(2);
howMany(3);
one
two
many
switch is now available in expression.
static void howMany(int k) {
System.out.println(
switch (k) {
case 1 -> "one"
case 2 -> "two"
default -> "many"
}
);
}
So you can also assign the result of a switch statement to a variable.
T result = switch (arg) {
case L1 -> e1;
case L2 -> e2;
default -> e3;
};
The "yield" keyword has been added.
int j = switch (day) {
case MONDAY -> 0;
case TUESDAY -> 1;
default -> {
int k = day.toString().length();
int result = f(k);
yield result; //Set the return value of the switch statement
}
};
"Yield" can also be used in switch statements of "case L:" expressions.
int result = switch (s) {
case "Foo":
yield 1;
case "Bar":
yield 2;
default:
System.out.println("Neither Foo nor Bar, hmmm...");
yield 0;
};
Recommended Posts