Null case in switch
Handle null directly as a switch case — no separate guard needed.
Porównanie kodu
✕ Java 8
// Must check before switch
if (status == null) {
return "unknown";
}
return switch (status) {
case ACTIVE -> "active";
case PAUSED -> "paused";
default -> "other";
};
✓ Java 21+
return switch (status) {
case null -> "unknown";
case ACTIVE -> "active";
case PAUSED -> "paused";
default -> "other";
};
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Explicit
null handling is visible right in the switch.
No NPE
Switch on a null value won't throw NullPointerException.
All-in-one
All cases including null in a single switch expression.
Stare podejście
Guard Before Switch
Nowoczesne podejście
case null
Od JDK
21
Poziom trudności
Początkujący
Wsparcie JDK
Null case in switch
Dostępne
Widely available since JDK 21 LTS (Sept 2023)
Jak to działa
Pattern matching switch can match null as a case label. This eliminates the need for a null check before the switch and makes null handling explicit and visible.
Powiązana dokumentacja