
Pattern Matching with Record Patterns
and Paris Monuments
In Java, record patterns allow you to check if an object is an instance of a record, and if so, automatically extract its component values for further use. This is especially useful when you work with structured data.
🔵 For more background, you can refer to JEP 440.
Let’s discover it with an example using famous Paris monuments!
Simple Record Pattern Example
Imagine we define a record Monument:
Now, we want to print a message if the object is a Monument. Using record patterns, we can extract the name and year directly:
If you pass a Monument like the Eiffel Tower, it will print:
Notice that null will never match a record pattern — so no worries about null pointer exceptions here.
Using a Type Pattern Instead
You could also do it in a slightly different way by first capturing the Monument, then calling its methods:
Both approaches work! The record pattern version is just more compact when you need to immediately extract fields.
Working with Generic Records
Suppose you have a generic record like a box containing a monument:
You can pattern match a specific type inside the box:
⚠️ Important:
You must avoid unsafe casts. If you try to pattern match on a Box without a guaranteed type, it won’t compile.Example of wrong code:
Type Inference with var
You don't always need to repeat the types. Java can infer them for you with var:
Shorter and cleaner!
Nested Record Patterns: Paris in Layers
You can even nest record patterns when working with more complex structures!
Imagine:
Now, let's print the latitude of the northern monument:
Example:
If north represents the Arc de Triomphe and south the Louvre Museum, the program will print the Arc’s latitude!
Nested Generic Example
You can nest patterns with generic types too. Example:
Here, even though you have a box inside a box, Java infers everything!
Summary
✨ With record patterns and type inference, Java makes it easier to work with structured data — whether you're describing points on a map or historic Paris monuments.
You can:
🟣 Check and extract values in one line
🟣 Avoid verbose code
🟣 Safely navigate nested structures