How to Write Clean Code with Record Patterns in Java 21
Java Introduced record type
in Java 14. In version 21, Java introduced record patterns that de-structures the instances of record
classes and enable more sophisticated data queries.
Published in
3 min readJan 1, 2024
Java introduced a special type called record in Java 14. Records are a new kind of type declaration which is a restricted form of class types. A record is concise than a class, and its main purpose is to hold data.
The following is an example of a record type definition:
// Defining a record type
record Point(int x, int y)
The above code snippet does the following:
- It declares a record type named Point.
- It includes private final fields for variables x and y.
- Includes accessor methods for variable x and y with return type int with method names x() and y().
- Provides a public constructor with members x and y.
- Includes implementation of equals(), hashCode(), and toString() methods.
In this article, we’ll discuss the record patterns introduced in Java 21. Record patterns were included as a preview feature in Java 19 with JEP 405…