When using instanceof as a pattern match operator in an if-statement, the code fails to compile if we use the boolean logical operator &, but succeeds if using &&.
This DOES compile:
Number n = Integer.valueOf(9);
if (n instanceof Integer i) {
i = 3;
}
This DOES NOT compile:
Number n = Integer.valueOf(9);
if (n instanceof Integer i & true) {
i = 3;
}
// Hello.java:6: error: cannot find symbol
// i = 3;
// ^
// symbol: variable i
// location: class Hello
// 1 error
This DOES compile:
Number n = Integer.valueOf(9);
if (n instanceof Integer i && true) {
i = 3;
}
Can anyone explain why the second code snippet does not compile?
I think this may be because of section 6.3.1 of the JLS, which says that
Since the boolean logical operator
&is not listed, the expressionn instanceof Integer i & truedoes not introduce a pattern variable that can subsequently be seen in the body of theifstatement, hence the compiler's error message "cannot find symbol".