Pattern matching for switch (Java 21 — JEP 441) cho switch test theo kiểu, vừa bind biến đã ép kiểu, vừa cho thêm when lọc — gom được chuỗi if-instanceof dài.
double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square sq -> sq.side() * sq.side();
case Triangle t when t.base() > 0
-> 0.5 * t.base() * t.height();
case Triangle t -> 0;
};
}Kết hợp với sealed: compiler bắt buộc xử lý mọi subtype, bỏ sót là compile error (không phải bug runtime).
Đi kèm record pattern (JEP 440) bóc field thẳng trong pattern: case Circle(double r) -> .... Ứng viên migrate đầu: code cũ dùng instanceof + cast dày đặc.
Pattern matching for switch (Java 21 — JEP 441) lets switch test by type, bind a properly-cast variable, and add a when guard — collapsing long if-instanceof chains.
double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square sq -> sq.side() * sq.side();
case Triangle t when t.base() > 0
-> 0.5 * t.base() * t.height();
case Triangle t -> 0;
};
}Combined with sealed: the compiler forces you to handle every subtype, missing one is a compile error (not a runtime bug).
- Pairs with record patterns (JEP 440) to destructure fields in the pattern:
case Circle(double r) -> .... - First migration candidate: legacy code peppered with
instanceof+ cast.