Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lombok's @Value not working with additional constructor

I am using Lombok’s @Value annotation like this:

@Value
public class Foo {
    int x;
    int y;
}

As per the official documentation, this should be equivalent to @Getter @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) @AllArgsConstructor @ToString @EqualsAndHashCode. So far everything looks good, I can check the code with a little test and see that the @AllArgsConstrucotr is present.

However, I need to add an additional constructor that calls the All-Args Constructor and this breaks everything:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Value
public class Foo {
    int x; // IDE warning: Variable 'x' might not have been initialized
    int y; // IDE warning: Variable 'y' might not have been initialized
    
    public Foo(Bar bar) {
        this(bar.getA(), bar.getB()); // IDE warning: Expected 1 arguments but found 2
    }
}

If I’m trying to run a simple test, I’ll get a compilation error:

  required: ...Bar
  found:    int,int
  reason: actual and formal argument lists differ in length

In short, the @AllArgsConstructor is no longer generated, and I need manually add it back in order to enforce lombok to generate it:

@Value
@AllArgsConstructor
public class Foo {
    //...
}

Is there a better way of doing it? Can I enforce this through some configuration? Is this a known issue in Lombok? The version I am using in this project is 1.18.18

>Solution :

Your quote from the lombok documentation is incomplete. The actual lombok documentation is very clear about this behaviour:

In practice, @Value is shorthand for: final @ToString @EqualsAndHashCode @AllArgsConstructor @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @Getter, except that explicitly including an implementation of any of the relevant methods simply means that part won’t be generated and no warning will be emitted.

[…]

Also, any explicit constructor, no matter the arguments list, implies lombok will not generate a constructor.

And the next sentence contains the solution:

If you do want lombok to generate the all-args constructor, add @AllArgsConstructor to the class.

If you need the additional constructor, you must add the @AllArgsConstructor annotation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading