Lombok builder methods return the instance of the class itself instead of returning builder class Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!Java method to format String fieldsHow to get a class instance of generics type TIs this a valid Java implementation of an immutable class and the Builder pattern?org.springframework.orm.hibernate3.HibernateQueryException - HibernateTemplateCreate the perfect JPA entityInner classes defined inside a block like a method in Java can not have any modifiers not even public. Why?How to add integer constructors and public signatures javaMethod override returns nullRequired arguments with a lombok @BuilderAndroid sqlite searching two columns

What's the meaning of 間時肆拾貳 at a car parking sign

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

Should I use a zero-interest credit card for a large one-time purchase?

A coin, having probability p of landing heads and probability of q=(1-p) of landing on heads.

When do you get frequent flier miles - when you buy, or when you fly?

Identify plant with long narrow paired leaves and reddish stems

What to do with chalk when deepwater soloing?

List *all* the tuples!

How to align text above triangle figure

ListPlot join points by nearest neighbor rather than order

How to call a function with default parameter through a pointer to function that is the return of another function?

How to react to hostile behavior from a senior developer?

How widely used is the term Treppenwitz? Is it something that most Germans know?

Can an alien society believe that their star system is the universe?

Can I cast Passwall to drop an enemy into a 20-foot pit?

What LEGO pieces have "real-world" functionality?

Fundamental Solution of the Pell Equation

51k Euros annually for a family of 4 in Berlin: Is it enough?

Sci-Fi book where patients in a coma ward all live in a subconscious world linked together

Can any chord be converted to its roman numeral equivalent?

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

Why is my conclusion inconsistent with the van't Hoff equation?

Identifying polygons that intersect with another layer using QGIS?

Why light coming from distant stars is not discreet?



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



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!Java method to format String fieldsHow to get a class instance of generics type TIs this a valid Java implementation of an immutable class and the Builder pattern?org.springframework.orm.hibernate3.HibernateQueryException - HibernateTemplateCreate the perfect JPA entityInner classes defined inside a block like a method in Java can not have any modifiers not even public. Why?How to add integer constructors and public signatures javaMethod override returns nullRequired arguments with a lombok @BuilderAndroid sqlite searching two columns



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















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.lastName("Bob").age(31);.



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










share|improve this question



















  • 1





    Builder's designed for exactly this use case, you just write it slightly differently: User.builder().firstName("Tom").age(30).build();

    – jonrsharpe
    Mar 17 at 19:28











  • @jonrsharpe But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:37











  • That's right, builder is a creation pattern. What exactly are you trying to achieve here?

    – jonrsharpe
    Mar 17 at 19:38











  • @jonrsharpe I edited the description a little, after user is initialized, I can still modify it by user.lastName("Bob").age(31);

    – coderz
    Mar 17 at 19:41











  • Why not call setters at that point?

    – jonrsharpe
    Mar 17 at 19:41

















0















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.lastName("Bob").age(31);.



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










share|improve this question



















  • 1





    Builder's designed for exactly this use case, you just write it slightly differently: User.builder().firstName("Tom").age(30).build();

    – jonrsharpe
    Mar 17 at 19:28











  • @jonrsharpe But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:37











  • That's right, builder is a creation pattern. What exactly are you trying to achieve here?

    – jonrsharpe
    Mar 17 at 19:38











  • @jonrsharpe I edited the description a little, after user is initialized, I can still modify it by user.lastName("Bob").age(31);

    – coderz
    Mar 17 at 19:41











  • Why not call setters at that point?

    – jonrsharpe
    Mar 17 at 19:41













0












0








0








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.lastName("Bob").age(31);.



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










share|improve this question
















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.lastName("Bob").age(31);.



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







java lombok






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 17 at 19:39







coderz

















asked Mar 17 at 19:26









coderzcoderz

2,47462949




2,47462949







  • 1





    Builder's designed for exactly this use case, you just write it slightly differently: User.builder().firstName("Tom").age(30).build();

    – jonrsharpe
    Mar 17 at 19:28











  • @jonrsharpe But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:37











  • That's right, builder is a creation pattern. What exactly are you trying to achieve here?

    – jonrsharpe
    Mar 17 at 19:38











  • @jonrsharpe I edited the description a little, after user is initialized, I can still modify it by user.lastName("Bob").age(31);

    – coderz
    Mar 17 at 19:41











  • Why not call setters at that point?

    – jonrsharpe
    Mar 17 at 19:41












  • 1





    Builder's designed for exactly this use case, you just write it slightly differently: User.builder().firstName("Tom").age(30).build();

    – jonrsharpe
    Mar 17 at 19:28











  • @jonrsharpe But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:37











  • That's right, builder is a creation pattern. What exactly are you trying to achieve here?

    – jonrsharpe
    Mar 17 at 19:38











  • @jonrsharpe I edited the description a little, after user is initialized, I can still modify it by user.lastName("Bob").age(31);

    – coderz
    Mar 17 at 19:41











  • Why not call setters at that point?

    – jonrsharpe
    Mar 17 at 19:41







1




1





Builder's designed for exactly this use case, you just write it slightly differently: User.builder().firstName("Tom").age(30).build();

– jonrsharpe
Mar 17 at 19:28





Builder's designed for exactly this use case, you just write it slightly differently: User.builder().firstName("Tom").age(30).build();

– jonrsharpe
Mar 17 at 19:28













@jonrsharpe But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

– coderz
Mar 17 at 19:37





@jonrsharpe But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

– coderz
Mar 17 at 19:37













That's right, builder is a creation pattern. What exactly are you trying to achieve here?

– jonrsharpe
Mar 17 at 19:38





That's right, builder is a creation pattern. What exactly are you trying to achieve here?

– jonrsharpe
Mar 17 at 19:38













@jonrsharpe I edited the description a little, after user is initialized, I can still modify it by user.lastName("Bob").age(31);

– coderz
Mar 17 at 19:41





@jonrsharpe I edited the description a little, after user is initialized, I can still modify it by user.lastName("Bob").age(31);

– coderz
Mar 17 at 19:41













Why not call setters at that point?

– jonrsharpe
Mar 17 at 19:41





Why not call setters at that point?

– jonrsharpe
Mar 17 at 19:41












2 Answers
2






active

oldest

votes


















3














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.






share|improve this answer

























  • But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:35












  • @coderz then remove final keywords. @Data gives you setters.

    – Bohemian
    Mar 17 at 19:38











  • @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

    – dehasi
    Mar 17 at 19:39






  • 1





    @coderz try @Accessors(fluent = true)

    – Bohemian
    Mar 17 at 19:41











  • @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

    – coderz
    Mar 17 at 19:43


















1














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!






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55211010%2flombok-builder-methods-return-the-instance-of-the-class-itself-instead-of-return%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    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.






    share|improve this answer

























    • But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

      – coderz
      Mar 17 at 19:35












    • @coderz then remove final keywords. @Data gives you setters.

      – Bohemian
      Mar 17 at 19:38











    • @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

      – dehasi
      Mar 17 at 19:39






    • 1





      @coderz try @Accessors(fluent = true)

      – Bohemian
      Mar 17 at 19:41











    • @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

      – coderz
      Mar 17 at 19:43















    3














    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.






    share|improve this answer

























    • But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

      – coderz
      Mar 17 at 19:35












    • @coderz then remove final keywords. @Data gives you setters.

      – Bohemian
      Mar 17 at 19:38











    • @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

      – dehasi
      Mar 17 at 19:39






    • 1





      @coderz try @Accessors(fluent = true)

      – Bohemian
      Mar 17 at 19:41











    • @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

      – coderz
      Mar 17 at 19:43













    3












    3








    3







    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.






    share|improve this answer















    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 17 at 20:37

























    answered Mar 17 at 19:33









    BohemianBohemian

    301k65431573




    301k65431573












    • But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

      – coderz
      Mar 17 at 19:35












    • @coderz then remove final keywords. @Data gives you setters.

      – Bohemian
      Mar 17 at 19:38











    • @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

      – dehasi
      Mar 17 at 19:39






    • 1





      @coderz try @Accessors(fluent = true)

      – Bohemian
      Mar 17 at 19:41











    • @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

      – coderz
      Mar 17 at 19:43

















    • But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

      – coderz
      Mar 17 at 19:35












    • @coderz then remove final keywords. @Data gives you setters.

      – Bohemian
      Mar 17 at 19:38











    • @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

      – dehasi
      Mar 17 at 19:39






    • 1





      @coderz try @Accessors(fluent = true)

      – Bohemian
      Mar 17 at 19:41











    • @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

      – coderz
      Mar 17 at 19:43
















    But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:35






    But once user is built, I'm not able to modify it with same manner, say user.firstName("foo2").age(23) is not possible.

    – coderz
    Mar 17 at 19:35














    @coderz then remove final keywords. @Data gives you setters.

    – Bohemian
    Mar 17 at 19:38





    @coderz then remove final keywords. @Data gives you setters.

    – Bohemian
    Mar 17 at 19:38













    @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

    – dehasi
    Mar 17 at 19:39





    @coderz Builders are used to make classes immutable. if you need mutability, add just @Getter and @Setter annotations. And even better not use lombok:

    – dehasi
    Mar 17 at 19:39




    1




    1





    @coderz try @Accessors(fluent = true)

    – Bohemian
    Mar 17 at 19:41





    @coderz try @Accessors(fluent = true)

    – Bohemian
    Mar 17 at 19:41













    @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

    – coderz
    Mar 17 at 19:43





    @Bohemian @Accessors(fluent = true) is exactly what I want, it works! Can you edit your answer so that I accept it?

    – coderz
    Mar 17 at 19:43













    1














    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!






    share|improve this answer



























      1














      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!






      share|improve this answer

























        1












        1








        1







        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!






        share|improve this answer













        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!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 9:10









        Avelino CollarAvelino Collar

        113




        113



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55211010%2flombok-builder-methods-return-the-instance-of-the-class-itself-instead-of-return%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해