library
intermediatePattern Matching for instanceof (Java 16)
Eliminate explicit casts after instanceof checks using pattern variables.
Pattern matching for instanceof (preview in Java 14, stable in Java 16) combines the type check and cast into a single operation:
Like a customs officer who checks your passport (instanceof) and stamps it (cast) in one step, handing back a 'verified citizen' badge (pattern variable) you can use inside the country (true scope).
Key Concepts
1
Before: if (obj instanceof String) { String s = (String) obj; use(s); }
After: if (obj instanceof String s) { use(s); }
2
The pattern variable s is automatically cast and available within the scope where the pattern match is guaranteed to be true.
3
Scoping rules:
- In if-then: the variable is in scope in the if-body
- In if-then-else: the variable is NOT in scope in the else-body
- With &&: obj instanceof String s && s.length() > 0 — s is in scope after &&
- With ||: obj instanceof String s || ... — s is NOT in scope after || (match not guaranteed)
- Negation: if (!(obj instanceof String s)) return; — s is in scope AFTER the if (flow scoping)
4
This works with equals methods:
public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}
5
Combined with sealed classes and switch (Java 21), pattern matching enables powerful, type-safe dispatch without visitor patterns.