Is this functionality going to be put into a later Java version?
Can someone explain why I can\'t do this, as in, the technical way Java\'s switch
state
JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.
Now you can:
case L ->
):
The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.
To yield a value from a switch expression, the
break
with value statement is dropped in favor of ayield
statement.
So the demo from the answers (1, 2) might look like this:
public static void main(String[] args) {
switch (args[0]) {
case "Monday", "Tuesday", "Wednesday" -> System.out.println("boring");
case "Thursday" -> System.out.println("getting better");
case "Friday", "Saturday", "Sunday" -> System.out.println("much better");
}