Pattern matching in switch
Replace if-else instanceof chains with clean switch type patterns.
Porównanie kodu
✕ Java 8
String format(Object obj) {
if (obj instanceof Integer i)
return "int: " + i;
else if (obj instanceof Double d)
return "double: " + d;
else if (obj instanceof String s)
return "str: " + s;
return "unknown";
}
✓ Java 21+
String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Double d -> "double: " + d;
case String s -> "str: " + s;
default -> "unknown";
};
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Structured dispatch
Switch makes the branching structure explicit and scannable.
Expression form
Returns a value directly — no mutable variable needed.
Exhaustiveness
The compiler ensures all types are handled.
Stare podejście
if-else Chain
Nowoczesne podejście
Type Patterns
Od JDK
21
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Pattern matching in switch
Dostępne
Widely available since JDK 21 LTS (Sept 2023)
Jak to działa
Pattern matching in switch lets you match on types directly, combining the type test, cast, and binding in one concise case label. The compiler checks completeness.
Powiązana dokumentacja