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?
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:
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.