Record Patterns Deconstruct Nested Shapes
Deconstruct records directly in case labels and nest patterns so extraction and validation happen in one exhausted switch.
Code
public class PricingEngine {
record Money(long cents) { }
record Item(String sku, Money price) { }
record Order(String id, Item item, int quantity) { }
static String describe(Object value) {
// 解构直接写进 case:类型判定与字段提取一步完成
return switch (value) {
case Order(String id, Item(String sku, Money(long cents)), int qty)
when qty > 10 -> id + ": bulk " + sku + " x" + qty + " @" + cents;
case Order(String id, Item(String sku, Money(long cents)), int qty)
-> id + ": " + sku + " x" + qty + " @" + cents;
case Money(long cents) -> "loose change " + cents;
default -> "unknown payload";
};
}
public static void main(String[] args) {
System.out.println(describe(new Order("A-1", new Item("pen", new Money(199)), 1)));
System.out.println(describe(new Order("A-2", new Item("mug", new Money(899)), 24)));
System.out.println(describe(new Money(50)));
System.out.println(describe("not an order"));
}
}Deconstruction in case labels
The switch in describe() unpacks Order(String id, Item(String sku, Money(long cents)), int qty) directly in the case label, so type testing and field extraction happen in one step with no manual casts or accessor chains.
Guards and ordering
The guarded case (when qty > 10) must precede the unguarded one, or it would never be reached; both produce id: sku xqty @cents strings, the bulk variant with the bulk marker.
Exhaustiveness
Money and the default arm keep the switch closed over the inputs the demo passes — a loose Money(50) prints loose change 50 and the string input prints unknown payload.
Interactive Tools for This Topic
FAQ
- Why must the guarded case come first?
- Pattern matching picks the first matching label; once the unguarded Order case matches, the when-clause variant would never run.
- What does nesting record patterns buy?
- One label can destructure the whole nested value (order, item, money) instead of chaining accessor calls or casting stepwise.
Report a problem with this exampleOpens a pre-filled issue on GitHub.