Video in progress
What are record patterns in Java 21, and how do they unpack nested data?
A record pattern unpacks a record into its parts inside instanceof or switch: case Point(int x, int y). You can nest a pattern inside a pattern, and getter chains and casts go away.
📖 Answer
Say we have a model of payment events:
sealed interface Event permits Paid, Refunded {}
record Money(BigDecimal amount, String currency) {}
record Paid(String orderId, Money money) implements Event {}
record Refunded(String orderId, Money money, String reason) implements Event {}
Before Java 21:
if (e instanceof Paid p && p.money().currency().equals("UZS")) {
total = total.add(p.money().amount());
}
With record patterns:
switch (e) {
case Paid(var id, Money(var amt, var cur)) when cur.equals("UZS")
-> total = total.add(amt);
case Paid(var id, Money m) -> convertAndAdd(m);
case Refunded(var id, Money(var amt, var cur), var reason)
-> total = total.subtract(amt);
}
What to watch for:
- patterns call the accessor methods, they don't read the field directly;
- a nested record pattern doesn't match
null: ifmoneyisnull,Paid(var id, Money(...))doesn't match, but inPaid(var id, Money m)themarrives asnull; - if you use
var, the type is taken from the record declaration; - if you don't need a component, from Java 22 you can write
_(an unnamed pattern); in Java 21 it's still a preview.
Together with a sealed interface, the compiler checks that all cases are covered, so no default is needed.
Sign up to mark studied questions and save your progress.