Language Początkujący

Combine type check and cast in one step with pattern matching.

✕ Java 8
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}
✓ Java 16+
if (obj instanceof String s) {
    IO.println(s.length());
}
Widzisz problem z tym kodem? Daj nam znać.
🔄

No redundant cast

Type check and variable binding happen in a single expression.

📏

Fewer lines

One line instead of two — the cast line disappears entirely.

🛡️

Scope safety

The pattern variable is only in scope where the type is guaranteed.

Stare podejście
instanceof + Cast
Nowoczesne podejście
Pattern Variable
Od JDK
16
Poziom trudności
Początkujący
Pattern matching for instanceof
Dostępne

Widely available since JDK 16 (March 2021)

Pattern matching for instanceof eliminates the redundant cast after a type check. The variable is automatically scoped to where the pattern matches, making code safer and shorter.

Udostępnij 𝕏 🦋 in