guards in non pattern switches
Remi Forax
forax at univ-mlv.fr
Thu Jun 10 10:25:25 UTC 2021
Only the pattern switch supports guards,
trying to use a guard inside a string switch, enum switch or int switch.
So with
public static void example3() {
enum Color { RED, BLACK }
var color = Color.RED;
var value = switch(color) {
case RED && color != null -> 1;
case RED -> 2;
case BLACK -> 3;
};
System.out.println("value " + value);
}
public static void example4() {
var aString = "bar";
var anotherValue = 4;
var value = switch(aString) {
case "foo" && anotherValue == 4 -> 1;
case "bar" -> 2;
default -> 3;
};
System.out.println("value " + value);
}
public static void example5() {
var aValue =10;
var anotherValue = 4;
var value = switch(aValue) {
case 42 && anotherValue == 4 -> 1;
case 10 -> 2;
default -> 3;
};
System.out.println("value " + value);
}
I get the following errors
PatternMatchingGuard.java:33: error: an enum switch case label must be the unqualified name of an enumeration constant
case RED && color != null -> 1;
^
PatternMatchingGuard.java:44: error: bad operand types for binary operator '&&'
case "foo" && anotherValue == 4 -> 1;
^
first type: String
second type: boolean
PatternMatchingGuard.java:55: error: bad operand types for binary operator '&&'
case 42 && anotherValue == 4 -> 1;
^
first type: int
second type: boolean
Note: PatternMatchingGuard.java uses preview features of Java SE 17.
Note: Recompile with -Xlint:preview for details.
3 errors
I believe that an error message saying that guards are not supported in enum switch, string switch and int switch is more user friendly.
regards,
Rémi
More information about the compiler-dev
mailing list