I have a list as
@Value
@Builder(toBuilder = true)
class Demo {
private BigInteger id;
@Singular
private List<String> name;
}
I have some data added in the name list. Now I want to set it to empty or null. How can I achieve it? As per my understanding if I m using @Singular annotation it makes the list immutable.
I m using Java with Lombok.
As per my understanding if I m using @Singular annotation it makes the list immutable.
It makes the list in the Demo
instance immutable. It does not make the list immutable in the builder; it simply changes the API of the builder.
From the documentation:
with the
@Singular
annotation, lombok will treat that builder node as a collection, and it generates 2 'adder' methods instead of a 'setter' method
As for emptying the list,
A 'clear' method is also generated.
In your case, clearNames
(the list field should be called names
, not name
, otherwise Lombok complains).
If you want a mutable instance, don't use @Singular
As per my understanding if I m using @Singular annotation it makes the list immutable
No, Lambok just create method for single add element, for you class (I strongly recommend change name to names). You just need to call method "clearNames"
@Value
@Builder(toBuilder = true)
class Demo {
private BigInteger id;
@Singular
private List<String> names;
}
Lambok generate following builder
public static class UserBuilder {
private BigInteger id;
private ArrayList<String> names;
UserBuilder() {
}
public User.UserBuilder name(String name) {
if (this.names == null) this.names = new ArrayList<String>();
this.names.add(name);
return this;
}
public User.UserBuilder names(Collection<? extends String> names) {
if (this.names == null) this.names = new ArrayList<String>();
this.names.addAll(names);
return this;
}
public User.UserBuilder clearNames() {
if (this.names != null)
this.names.clear();
return this;
}
...
public User build() {
...
}
public String toString() {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With