Search code examples
javabuilderlombok

Lombok @Builder does not create immutable objects?


In many sites, I saw lombok @Builder can be used to create immutable objects here(https://www.baeldung.com/lombok-builder-singular) and also many sites say Builder pattern is mainly used to create immutable objects.

TimeIntervalData td = TimeIntervalData.builder().endTime("12:00").startTime("10:00").build();
td.setEndTime("14:00");
System.out.println(td.getEndTime());

I am not sure how I can use setters on objects built using builders. Is there something I am missing here?


Solution

  • Yes lombok builder will not create immutable instances util user define the parameters in class as final, As per the docs from lombok.builder @Builder lets you automatically produce the code required to have your class be instantiable with code such as:

    Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();
    

    As per the docs it just creates inner static class with the same properties in the same way that mentioned in outer class

    A method annotated with @Builder (from now on called the target) causes the following 7 things to be generated:

    • An inner static class named FooBuilder, with the same type arguments as the static method (called the builder).
    • In the builder: One private non-static non-final field for each parameter of the target.
    • In the builder: A package private no-args empty constructor.
    • In the builder: A 'setter'-like method for each parameter of the target: It has the same type as that parameter and the same name. It returns the builder itself, so that the setter calls can be chained
    • In the builder: A build() method which calls the method, passing in each field. It returns the same type that the target returns
    • In the builder: A sensible toString() implementation.
    • In the class containing the target: A builder() method, which creates a new instance of the builder.

    But using @Singular with @Builder annotation for collection properties makes them singleton

    By annotating one of the parameters (if annotating a method or constructor with @Builder) or fields (if annotating a class with @Builder) with the @Singular annotation, lombok will treat that builder node as a collection, and it generates 2 'adder' methods instead of a 'setter' method. One which adds a single element to the collection, and one which adds all elements of another collection to the collection. No setter to just set the collection (replacing whatever was already added) will be generated.

    @Singular can only be applied to collection types known to lombok.