Nested Record Patterns in Java 21: Cleaner Code

🧩 Part 2 — Nested Record Patterns (Java 21) Nested Record Patterns — The Next Step in Cleaner Java Last week, I showed how Java 21 lets you unpack records directly inside an if or switch. This week, let’s go a level deeper — nested record patterns. Suppose we have: public record Point(int x, int y) {} public record Rectangle(Point topLeft, Point bottomRight) {} Before (manual unpacking): if (shape instanceof Rectangle rect) { Point tl = rect.topLeft(); Point br = rect.bottomRight(); System.out.println("Top left: " + tl.x() + "," + tl.y()); } After (nested pattern): if (shape instanceof Rectangle(Point(int x1, int y1), Point(int x2, int y2))) { System.out.println("Top left: " + x1 + "," + y1); System.out.println("Bottom right: " + x2 + "," + y2); } You can destructure both levels in one clean statement — no casts, no temp variables, and still fully type-safe. It’s one of those features that feels small but reads like modern Java should. 👉 What’s your take — elegant or too much magic? #Java #Java21 #Records #PatternMatching #CleanCode #SoftwareEngineering

To view or add a comment, sign in

Explore content categories