Week 144 — What is a record pattern and how can one use it?
Question of the Week #144
What is a record pattern and how can one use it?
3 Replies
Record patterns allow matching an object against a record and extracting the components if the match succeeds. They can be used in both
instanceof
and switch
statements/expressions.
For example, take the following record:
Objects of that class can be matched against that record as follows:
Patterns can also be nested. For example, consider this record containing a component of type
Person
:
Records like these can be matched as follows:
📖 Sample answer from dan1st
If looked at in terms of objects, a
record
is a value object with fields that are implicitly final, and several pre-generated methods, such as equals
and hashCode
that make sense for comparing records.
The more likely answer, if viewing the question from the point of view of pattern matching, is the use of instanceof
to cast an object to a record type and use the fields of that record implicitly. This can even be done recursively. Example below:
Foo.java
Bar.java
Main.java
Submission from awesomealec1