As you know, Java 14 introduced Switch Expressions, switch
statements that return a value. (See JEP 361.)
But it doesn't seem to work with case
statements that have code blocks. I'm not sure if I don't have the syntax right or this is disallowed.
I'm curious because it would be inconsistent with non r-value switch statements (first example). Plus I've seen this in other languages.
static void foo(String x) {
// this works
switch(x) {
case "hi" -> {
System.out.print("got hi");
System.out.println("hello");
}
default -> System.out.println("bye");
}
// this works
var y = switch(x) {
case "hi" -> "hello";
default -> "bye";
};
// is this possible?
var z = switch(x) {
case "hi" -> {
System.out.println("got hi");
return "hello"; // return "hello" to the z
}
default -> "bye";
};
}
yield
, not return
Java 14 introduced a new yield
statement as part of JEP 361: Switch Expressions.
Instead of return
, use the restricted identifier yield
.
See The Java® Language Specification for details.
Example code:
var z = switch(x) {
case "hi" -> {
System.out.println("got hi");
yield "hello";
}
default -> "bye";
};
And this doesn't just work with switches with -> { ... }
. You can use it in a labeled switch expression too:
var z = switch(x) {
case "hi":
System.out.println("got hi");
yield "hello";
default:
yield "bye"
};
See also part 6 Switch Expressions of Java Language Updates.