Skip to content
Advertisement

Shorthand class constructor member initialisation

Writing simple constructors in Java is pretty verbose. For each field that needs to be initialised you need to write the variable name four times, e.g. like so:

class X {
    int y;
    public X(int y) {
        this.y = y;
    }
}

Is there a shorthand for that like e.g. in Kotlin?

This question was asked before here: Shorthand class constructor field initialisation

But that was way back in 2013 (6 Java versions ago) and the comments in this (Ask for update to answers) meta post say to post another question to request an answer for a newer version.

Also, the original question wasn’t really answered since the answers focussed on chaining constructors instead. And according to the rules, a question that has not been answered cannot be the reason that another question is flagged as a duplicate.

Advertisement

Answer

Project Lombok makes Java much less verbose. Using it’s annotations you can skip a lot of Java Boilerplate.

For constructors there are @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement