capypad
0 day streak
java / expert
Snippet

Nested Record Patterns for Data Extraction

Record patterns (Java 21) allow for the deep deconstruction of complex data structures directly within 'instanceof' or 'switch' statements. This eliminates boilerplate casting and accessor calls, making the code more declarative and less error-prone.

snippet.java
java
1
2
3
4
5
6
7
8
public record Customer(String name, String email) {}
public record Order(Customer customer, double total) {}
 
void printOrderInfo(Object obj) {
if (obj instanceof Order(Customer(var name, var email), var total)) {
System.out.printf("Customer %s (%s) spent %.2f%n", name, email, total);
}
}
Breakdown
1
if (obj instanceof Order(Customer(var name, var email), var total))
Matches the object against a nested record structure and extracts fields into local variables.
2
System.out.printf("Customer %s...", name, email, total);
Uses the extracted variables directly without calling .customer() or .name().