Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting null or empty for @singular list in lombok

Tags:

java

lombok

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.

like image 871
Gopal Singhania Avatar asked Jan 26 '23 19:01

Gopal Singhania


2 Answers

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

like image 101
Michael Avatar answered Jan 28 '23 09:01

Michael


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() {
           ...
       }
   }
like image 43
Slava Vedenin Avatar answered Jan 28 '23 09:01

Slava Vedenin