[patterns] Mixed constant-pattern cases
Tagir Valeev
amaembo at gmail.com
Mon Aug 14 12:08:37 UTC 2023
Hello!
I've noticed that javac accepts this code:
enum X {A, B}
void test(Object obj) {
switch (obj) {
case String _, X.B -> System.out.println("B or String");
default -> System.out.println("other");
}
}
public static void main(String[] args) {
new Test().test("ddd");
}
At the same time, it rejects if the order of label elements is reverted:
void test(Object obj) {
switch (obj) {
case X.B, String _ -> System.out.println("B or String");
default -> System.out.println("other");
}
}
Now "java: <identifier> expected" compilation error is displayed. So,
I've reported a javac issue here:
https://bugs.openjdk.org/browse/JDK-8314216
However, the expected behavior could be discussed. As per spec draft
[1], patterns and constants cannot be mixed in the same switch label:
it's either "case CaseConstant {, CaseConstant}", or "case
CasePattern{, CasePattern } [ Guard ]". However, mixing them might be
useful, and it already partially works in javac. Probably it would be
good to update this in the spec?
With best regards,
Tagir Valeev
[1] https://cr.openjdk.org/~abimpoudis/unnamed/jep443-20230322/specs/unnamed-jls.html#jls-14.11.1
More information about the amber-spec-experts
mailing list