Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Lombok @Builder not compatible with this constructor?

Tags:

java

lombok

I have this simple code:

@Data @Builder public class RegistrationInfo {      private String mail;     private String password;      public RegistrationInfo(RegistrationInfo registrationInfo) {         this.mail = registrationInfo.mail;         this.password = registrationInfo.password;     } } 

First I was using only the @Builder Lombok annotation and everything was fine. But I added the constructor and the code does not compile any more. The error is:

Error:(2, 1) java: constructor RegistrationInfo in class com.user.RegistrationInfo cannot be applied to given types;   required: com.user.RegistrationInfo   found: java.lang.String,java.lang.String   reason: actual and formal argument lists differ in length   

So I have two questions:

  1. Why is Lombok @Builder not compatible with this constructor?
  2. How do I make the code compile taking into account that I need both the builder and the constructor?
like image 681
IKo Avatar asked Jul 01 '18 10:07

IKo


People also ask

What does @builder do in Lombok?

When we annotate a class with @Builder, Lombok creates a builder for all instance fields in that class. We've put the @Builder annotation on the class without any customization. Lombok creates an inner static builder class named as StudentBuilder. This builder class handles the initialization of all fields in Student.

What is @builder annotation in Lombok?

Lombok's @Builder annotation is a useful technique to implement the builder pattern that aims to reduce the boilerplate code. In this tutorial, we will learn to apply @Builder to a class and other useful features. Ensure you have included Lombok in the project and installed Lombok support in the IDE.

Does @builder require AllArgsConstructor?

Martin Grajcar. Your @Builder needs an @AllArgsConstructor (add it; feel free to make it private).

What is difference between @builder and SuperBuilder?

The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.


1 Answers

You can either add an @AllArgsConstructor annotation, because

@Builder generates an all-args constructor iff there are no other constructors defined.

(Quotting @Andrew Tobilko)

Or set an attribute to @Builder : @Builder(toBuilder = true) This give you the functionality of a copy constructor.

@Builder(toBuilder = true) class Foo {     // fields, etc }  Foo foo = getReferenceToFooInstance(); Foo copy = foo.toBuilder().build(); 
like image 52
wdc Avatar answered Sep 21 '22 20:09

wdc