With the new Java 14 Record functionality, is it possible of creating multiples constructors for the same Record?

Tags: ,



I have a bunch of “data” classes using Lombok and I want to migrate all of them to use the new Record functionality available in Java 14. With the new Java 14 Record functionality, is it possible of creating multiples constructors for the same Record? If not, is there an alternative?

Answer

As of Java 15 (see JEP 384: Records (Second Preview)), you may have multiple constructors in records.

However, every constructor must delegate to the record’s canonical constructor, which may be explicitly defined or auto-generated.

An example:

public record Person(
    String firstName,
    String lastName
) {
    // Compact canonical constructor:
    public Person {
        // Validations only; fields are assigned automatically.
        Objects.requireNonNull(firstName);
        Objects.requireNonNull(lastName);

        // An explicit fields assignment, like
        //   this.firstName = firstName;
        // would be a syntax error in compact-form canonical constructor
    }

    public Person(String lastName) {
        // Additional constructors MUST delegate to the canonical constructor,
        // either directly:
        this("John", lastName);
    }

    public Person() {
        // ... or indirectly:
        this("Doe");
    }
}

Another example:

public record Person(
    String firstName,
    String lastName
) {
    // Canonical constructor isn't defined in code, 
    // so it is generated implicitly by the compiler.

    public Person(String lastName) {
        // Additional constructors still MUST delegate to the canonical constructor!
        // This works: 
        this("John", lastName);

        // (Re-)Assigning fields here directly would be a compiler error:
        // this.lastName = lastName; // ERROR: Variable 'lastName' might already have been assigned to
    }

    public Person() {
        // Delegates to Person(String), which in turn delegates to the canonical constructor: 
        this("Doe");
    }
}


Source: stackoverflow