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
Only certain kinds of boolean expressions are involved in introducing pattern variables and determining where those variables are definitely matched. If an expression is not a conditional-and expression, conditional-or expression, logical complement expression, conditional expression, instanceof expression, switch expression, or parenthesized expression, then no scope rules apply.
Since the boolean logical operator &
is not listed, the expression n instanceof Integer i & true
does not introduce a pattern variable that can subsequently be seen in the body of the if
statement, hence the compiler's error message "cannot find symbol".