Do you know Java: Records


Java 15 introduces record type.

Records are a new kind of class in the Java language. The purpose of a record is to declare that a small group of variables is to be regarded as a new kind of entity. As said in JEP 384.

Simple data carrier classes contain too much boilerplate code compared to the data itself. Fields, getter, setters, ctors, toString, equals, hashCode. On the other hand, quite difficult to figure out what the class represents.

The new approach looks like the following

record Person(String name, int age) { }

This approach reminds me to data classes in Kotlin.

Record represents an immutable class, that has a ctor with parameters. Also has getters, and the classic three methods from Object that we override.

The type is final implicitly as well as the fields are.

Any record implicitly extends java.lang.Record and no explicit inheritance can be applied on them, though record accepts interface implementations.

record Person(String name, int age) implements Comparable<Person> {
    Person() {
        this("John Doe", 0);
    }

    @Override
    public int compareTo(Person other) {
        // ...
    }

}

Though, record is not intended to eliminate boilerplate code, these changes will decrease the code and make it more readable.

Further reading about JEP 384: Records

Code can be found: https://github.com/torokmark/do-you-know-java