Java 21
Record Patterns
Copyright © Seán Kennedy
Record Patterns
• Review “type patterns”
• Review “pattern matching”
• Review records
• Record Patterns
Copyright © Seán Kennedy
Type Patterns
• In Java 16, instanceof was extended to take a type pattern
and perform pattern matching. This simplified the instanceof-
and-cast idiom, resulting in more concise and less error-prone
code. String s is called a “type pattern”.
• As there is no casting with type patterns, the style is more
declarative.
3
Copyright © Seán Kennedy
Pattern Matching
• Pattern matching is done at runtime.
• If the pattern matches, then the instanceof expression is true
and the pattern variable ‘s’ now refers to whatever ‘obj’ refers
to.
String s is called a “type pattern”.
obj
String
“abc”
s
4
Copyright © Seán Kennedy
Records
• Records are a special type of class that save us a lot of
boilerplate code. They are considered “data carriers” and are
immutable.
• Records are specified using a record declaration where you
specify the “components” of the record.
• These components become final instance variables and
accessor methods having the same names as the components
are provided automatically.
• In addition, a (canonical) constructor, toString(), equals()
and hashCode() methods are also generated.
Copyright © Seán Kennedy
Records
Copyright © Seán Kennedy
Record Patterns
• Code that receives an instance of a record class, typically
extracts the data (components), using the built-in component
accessor methods.
• A “record pattern” consists of a type, a component pattern
list (which may be empty) and an optional identifier.
• A record pattern does two things for us:
1. checks if an object passes the instanceof test.
2. disaggregates the record instance into its components.
• Record patterns support nesting. 7
Copyright © Seán Kennedy
Record Patterns
Copyright © Seán Kennedy