Sub topic 10
Common scope mistakes
This chapter covers the compile errors people hit most often with binding variables. It assumes you know the type pattern syntax (o instanceof String s), the rules for &&, || and !, and how flow scoping works from the earlier chapters. Every example here uses Java 16 or later.
The one rule behind every error
A binding variable is in scope only where the compiler can prove the pattern matched. The compiler reasons about the boolean expression, not about what you meant. Each condition has a "when true" outcome and a "when false" outcome, and a binding variable belongs to exactly one of them.
| Expression | Binding is in scope when the expression is... | Column | Column |
|---|---|---|---|
| `o instanceof String s` | true | ||
| `!(o instanceof String s)` | false | ||
| `a && b` | true, if `a` or `b` introduces it when true | ||
| `a \ | \ | b` | false, if `a` or `b` introduces it when false |
Most scope errors come from picking the wrong row of this table.
Mistake 1: using the binding on the right side of `||`
The right side of a || b runs when a is false. A positive pattern on the left has not matched in that case, so the binding is not available.
static boolean check(Object o) {
// Does not compile: s is not in scope when the right side of || runs.
// return o instanceof String s || s.isEmpty();
return o instanceof String s && !s.isEmpty();
}Changing || to && changes the meaning. If you really want "not a string, or an empty string", negate the pattern. The binding is introduced when the left side is false, which is exactly when the right side runs.
static boolean isNotStringOrBlank(Object o) {
return !(o instanceof String s) || s.isBlank();
}This compiles. If o is not a String, the left side is true and the right side never runs. If o is a String, the left side is false, s is bound, and s.isBlank() is safe.
Mistake 2: using the binding in the `else` branch
The else branch of a positive test runs when the pattern did not match. With &&, it also runs when the pattern matched but the other condition failed, so the compiler cannot allow s there either.
static String describe(Object o) {
if (o instanceof String s && s.length() > 3) {
return "long string: " + s;
} else {
// s is not in scope here. The else runs when o is not a String,
// and also when o is a short String.
return "something else";
}
}The reverse form works, because the negated test binds s in the else:
static String describeNegated(Object o) {
if (!(o instanceof String s)) {
return "not a string";
} else {
return "string of length " + s.length();
}
}The conditional operator follows the same rule: o instanceof String s ? s.length() : 0 compiles, but using s in the 0 branch does not.
Mistake 3: expecting an early exit that does not exit
A negated pattern brings the binding into scope after the if only when the if body cannot complete normally. Complete normally means execution can fall through to the next statement. A return, a throw, break or continue (inside a loop) all prevent that. A println does not.
static int lengthOrZero(Object o) {
if (!(o instanceof String s)) {
System.out.println("not a string");
// No return here, so execution continues below with s unbound.
}
// Does not compile: s is not in scope, the body above can complete normally.
// return s.length();
return 0;
}The fix is to make the body leave the method:
static int lengthOrZero(Object o) {
if (!(o instanceof String s)) {
System.out.println("not a string");
return 0;
}
return s.length();
}Mistake 4: declaring a name that is already taken
A binding variable is a local variable, so it cannot reuse the name of another local variable or parameter that is in scope.
static void greet(Object o) {
String s = "default";
// Does not compile: variable s is already defined.
// if (o instanceof String s) { System.out.println(s); }
if (o instanceof String name) {
System.out.println("hello " + name);
} else {
System.out.println("hello " + s);
}
}The error also appears in less obvious places. In a long method, an earlier String s or an earlier pattern whose binding stays in scope after an early return can collide with a later pattern that picks the same name. When you see "already defined" on a pattern, search upward for the earlier s.
A binding variable may reuse the name of a field. It then hides the field inside its scope, which can be confusing:
final class Label {
private final String text = "field";
String show(Object o) {
if (o instanceof String text) {
// text is the binding here. this.text is the field.
return text + " / " + this.text;
}
return text; // the field again
}
}Hiding a field is legal, so no error warns you. Choose binding names that differ from field names.
Mistake 5: reassigning the binding variable
In Java 16 and later, a binding variable is not implicitly final. You may assign to it, like any local variable:
static String trimmed(Object o) {
if (o instanceof String s) {
s = s.trim();
return s;
}
return "";
}This compiles, but it has two costs. First, a reader who sees o instanceof String s assumes s names the matched value for the whole block. After the assignment it no longer does. Second, a variable that is assigned more than once is not effectively final, so a lambda or inner class cannot capture it:
static Runnable printer(Object o) {
if (o instanceof String s) {
s = s.trim();
// Does not compile: s is not effectively final, so the lambda cannot capture it.
// return () -> System.out.println(s);
String trimmed = s;
return () -> System.out.println(trimmed);
}
return () -> { };
}Introduce a new variable instead of reassigning. If you want the compiler to enforce this, declare the pattern with final:
static int finalLength(Object o) {
if (o instanceof final String s) {
// s = s.trim(); would not compile now
return s.length();
}
return -1;
}Reassignment can also break the early-return idiom. The compiler's scoping rules only look at where the pattern matched, so the binding stays in scope after the guard. A loop that reassigns the tested variable, however, can leave you with a binding that no longer describes the current value. Prefer a fresh pattern each time you test.
Mistake 6: assuming the binding outlives a loop condition
A while loop with a negated pattern can bring the binding into scope after the loop, but only when the loop has no break that leaves it early. The reasoning is the same as for the early return: the code after the loop runs only when the condition became false, which means the pattern matched.
static String firstString(java.util.Iterator<Object> it) {
Object o = null;
while (it.hasNext() && !((o = it.next()) instanceof String s)) {
// keep looking
}
return o instanceof String s ? s : "none";
}This example is hard to read, and that is the point. The compiler's reasoning is sound, but you should not write code that relies on it. A plain loop with a pattern inside the body is clearer, and the guideline holds for any scope trick: if you have to work out why the binding is in scope, the next reader will have to as well.
A quick checklist
When the compiler reports "cannot find symbol" on a binding variable, ask these questions in order:
- Does the code that uses
srun only after the pattern matched? - Is a
||or anelsebetween the pattern and the use? - If you rely on a negated early exit, does the
ifbody end inreturn,throw,breakorcontinue?
When it reports "already defined", look for an earlier local variable, parameter or binding with the same name.
Exercise
Which of the following methods compile? Explain each answer. static boolean a(Object o) { return o instanceof Integer i || i > 0; } static boolean b(Object o) { return !(o instanceof Integer i) || i > 0; } static int c(Object o) { if (!(o instanceof Integer i)) { throw new IllegalArgumentException(); } return i + 1; } static int d(Object o) { if (!(o instanceof Integer i)) { System.out.println("skip"); } return i + 1; }
Show answer
Methods b and c compile. Method a fails because the right side of || runs when the pattern did not match, so i is not in scope. Method b negates the pattern, so i is bound exactly when the left side is false, which is when the right side runs. Method c compiles because the if body ends in throw and cannot complete normally, so i is in scope after the statement. Method d fails because the body can complete normally, so i is not in scope at the return.
Exercise
The code below does not compile. Give two different fixes and say which you prefer. static String label(Object o) { String s = "unknown"; if (o instanceof String s) { return s.toUpperCase(); } return s; }
Show answer
The pattern variable s collides with the local variable s. Fix 1: rename the binding, for example o instanceof String text, and use text.toUpperCase(). Fix 2: rename the local variable, for example String fallback = "unknown". Renaming the binding is usually better here because the local variable has a meaning that outlasts the if statement, while the binding only exists to hold the matched value.