Cut Java 21 Record Pattern Matching Code in Half
This article demonstrates how Java 21's switch pattern matching and record deconstruction let you replace verbose instanceof checks with concise two‑line snippets, even for nested records, dramatically simplifying code that extracts fields from complex objects.
Java 21 introduces switch pattern matching and record deconstruction, allowing developers to replace lengthy instanceof checks with concise code.
record Point(int x, int y) {}
static void printSum(Object obj) {
if (obj instanceof Point p) {
int x = p.x();
int y = p.y();
System.out.println(x + y);
}
}Before Java 21, extracting the fields of a Point required four lines of code; with pattern matching it can be done in just two lines:
static void printSum(Object obj) {
if (obj instanceof Point(int x, int y)) {
System.out.println(x + y);
}
}In real projects records are often nested. Consider the following records:
record Size(int width, int height) {}
record Point(int x, int y) {}
record WindowFrame(Point origin, Size size) {}To print the height of the Size inside a WindowFrame the traditional approach would be:
if (obj instanceof WindowFrame wf) {
if (wf.size() != null) {
System.out.println("Height: " + wf.size().height());
}
}Java 21 allows nested deconstruction, reducing the above to a single check:
if (obj instanceof WindowFrame(Point origin, Size(int width, int height))) {
System.out.println("Height: " + height);
}The image below illustrates the record hierarchy used in the examples.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
