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:
@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
@AllArgsConstructorto the class.
If you need the additional constructor, you must add the @AllArgsConstructor annotation.