Primitive types in patterns
Pattern matching now works with primitive types, not just objects.
Porównanie kodu
✕ Java 8
String classify(int code) {
if (code >= 200 && code < 300)
return "success";
else if (code >= 400 && code < 500)
return "client error";
else
return "other";
}
✓ Java 25 (Preview)
String classify(int code) {
return switch (code) {
case int c when c >= 200
&& c < 300 -> "success";
case int c when c >= 400
&& c < 500 -> "client error";
default -> "other";
};
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
No boxing
Match primitives directly — no Integer wrapper needed.
Pattern consistency
Same pattern syntax for objects and primitives.
Better performance
Avoid autoboxing overhead in pattern matching.
Stare podejście
Manual Range Checks
Nowoczesne podejście
Primitive Patterns
Od JDK
25
Poziom trudności
Zaawansowany
Wsparcie JDK
Primitive types in patterns
Preview
Preview in JDK 25 (third preview, JEP 507). Requires --enable-preview.
Jak to działa
Java 25 extends pattern matching to primitive types. You can use int, long, double etc. in switch patterns with when guards, eliminating the need for boxing or manual range checks.
Powiązana dokumentacja