coderz
coderz

Reputation: 4989

Lombok builder methods return the instance of the class itself instead of returning builder class

I have a class User

public class User {
    private String firstName;
    private String lastName;
    private int age;

    public User withFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public User withLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public User withAge(int age) {
        this.age = age;
        return this;
    }
}

So I can initialize it use User user = new User().withFirstName("Tom").withAge(30);, and after user is initialized, I can still modify it by user.withLastName("Bob").withAge(31);.

How can I leverage Lombok to save the "withXXX" methods? @Builder is not designed for this use case.

Upvotes: 2

Views: 2002

Answers (1)

Bohemian
Bohemian

Reputation: 425033

Try this:

@Data
@Builder
@Accessors(fluent = true) // <— This is what you want
public class User {
    private final String firstName;
    private final String lastName;
    private final int age;
}

Then to use:

User user = User.builder()
    .firstName("foo")
    .lastName("bar")
    .age(22)
    .build();

And later:

user.setFirstName("baz").setAge(23); // fluent setters

Note how User can be made immutable (best practice) by making all fields final. If you want mutability, remove final keywords.

Upvotes: 5

Related Questions