Java 14 is introducing a new preview feature called Records. Records provide a nice compact syntax to declare classes that are supposed to be dumb data holders. That may not sound much impressive but by taking a look at how we define such classes now, you might change your mind:
One might argue that writing these sort of boilerplates are a breeze with the help of our modern IDEs. However, we still need to read them, right?
Anyway, we can rewrite the same code with Records like:
Java compiler generates the following methods for this simple one-liner:
- Simple methods to access Record Components, e.g.
- A simple
equalsimplementation that considers all record components while comparing.
equalscompatible implementation for
- A simple
toStringthat simply prints all components.
- and of course, a constructor!
Let’s create a new record object:
Then we can have fun with it:
Records are immutable constructs, so we can’t change them after construction! That is, Javac doesn’t generate setter methods for records.
As we mentioned earlier, Records are part of the preview features in Java 14. So we should use the
--enable-preview flag while compiling Records:
Same is true when we’re going use Records in JShell:
Except for a few limitations, Records are normal Java classes. Therefore, we can add members or logics just like what we did with normal classes. For example, in order to enforce a pre-condition while constructing a Record instance:
When we omit the parameter list in a custom constructor, then we’re practically enhancing the primary constructor. Suppose we violate this pre-condition:
It’s also possible to declare instance or static methods on Records:
The invocation is just like normal instance or static methods:
It’s not possible to declare instance fields inside Records. This is a by-design limitation to simplify the reasoning about Record’s state. As opposed to instance fields, it’s perfectly fine to declare static fields inside records.
This was a very gentle introduction to JEP 359. I’m going to work on another more in-depth article about Records, their class representation, indy, and other more low-level details. So stay tuned!