hvaminion
hvaminion

Reputation: 145

How to write a custom build() function for lombok , for a set datatype which has a singular annotation?

@ToString
@EqualsAndHashCode
@Getter
@Builder(builderClassName = "Builder")
public class elements{

  @Singular("item")
  private final Set<int> items;

  private final int b;

  public static final class Builder {

    public elements build(){

      return new elements(items, b);

    }
  }


}

The constructor works when there is no singular annotation , but when I have a singular annotation on the set, the constructor says it is not available.

Java.util.set cannot be Java.util.ArrayList

So, What is the correct way to call this constructor ?

Upvotes: 0

Views: 2818

Answers (1)

Jan Rieke
Jan Rieke

Reputation: 8042

When using @Singular, the build() method generated by lombok becomes quite complex (and other parts of the generated builder, too). Here is what lombok generates by default (extracted from the delombok output of your example):

    public Elements build() {
        java.util.Set<Integer> items;
        switch (this.items == null ? 0 : this.items.size()) {
        case 0: 
            items = java.util.Collections.emptySet();
            break;

        case 1: 
            items = java.util.Collections.singleton(this.items.get(0));
            break;

        default: 
            items = new java.util.LinkedHashSet<Integer>(this.items.size() < 1073741824 ? 1 + this.items.size() + (this.items.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
            items.addAll(this.items);
            items = java.util.Collections.unmodifiableSet(items);
        }
        return new Elements(items, b);
    }

You can use that as a starting point for your customized build() method.

Upvotes: 2

Related Questions