简体   繁体   中英

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.

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.

I was trying to find a solution for fluent setters returning a new instance so the instance stays immutable and I found Wither annotation from Lombok experimental features in combination with Value annotation from stable features.

Hope it could help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM