Java Records

Java 14 introduces a new language feature, a Record.

Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data.

The semantic goal of Records is to enable modeling data as data. Records are clear and concise declarations of shallowly-immutable, well-behaved nominal data aggregates.

A Record has a name and a state description. The state description declares the components of the record.
The classic example is a 2D point:

record Point(int x, int y) {}

A Record is a new kind of type declaration. It’s a restricted form of class similar to an enum. The API of a Record is defined by its representation unlike classes which have the ability to decouple API from representation. Therefore, a Record acquires the following members automatically:

  • A private final field for each component of the state description
  • A public read accessor method for each component of the state description
  • A public constructor, whose signature is the same as the state description
  • Implementations of equals() and hashCode()
  • An implementation of toString()

However, a Record has the following restrictions:

  • Cannot extend any class
  • Cannot be extended
  • Cannot have non-final instance fields

Records support all other features of normal classes. They can implement interfaces, have instance methods, constructors, all kinds of static members, annotations and everything else.

A more sophisticated example of how Records can help with modeling data would be the idea of describing a 3D object with a transform which has information about rotation, translation and scale.

record Rotator(int pitch, int roll, int yaw) {}
record Vector(int x, int y, int z) {}
record Transform(Rotator rotation, Vector translation, Vector scale) {}

No other code is needed to start using our transform data model:

Vector scale = new Vector(1, 1, 1);
Vector translation = new Vector(100, 0, 0);
Rotator rotation = new Rotator(0, 0, 90);
Transform t1 = new Transform(rotation, translation, scale);


The example above produces the following output:

Transform[rotation=Rotator[pitch=0, roll=0, yaw=90], translation=Vector[x=100, y=0, z=0], scale=Vector[x=1, y=1, z=1]]

How much code would be needed to achieve the same with normal classes is left to the imagination of the reader.

Of course, Records can be used for much more. Some of the obvious use-cases include:

  • Multiple return values or tuples
  • Data transfer objects
  • Compound map keys
  • Messages
  • Value wrappers

Leave a Reply

Your email address will not be published. Required fields are marked *