When using immutable collections (like Guava's ImmutableSet, ImmutableList, etc.) as property types, AutoValue allows your builder to be more flexible than the property type itself.
Flexible Setters
You can define builder methods that accept any type compatible with the collection's copyOf method (e.g., Set, Collection, Iterable, or Array). This prevents callers from having to manually construct the immutable collection type before calling the setter.
Accumulating Values with propertyBuilder()
To avoid passing all elements at once, you can define a method named {propertyName}Builder() (e.g., countriesBuilder()) that returns the collection's builder type.
Note: Using propertyBuilder() directly breaks the method chain. To maintain a fluent API, you can implement a public add{PropertyName}(T value) method that internally uses the collection builder.
@AutoValue
public abstract class Animal {
public abstract String name();
public abstract int numberOfLegs();
public abstract ImmutableSet<String> countries();
public static Builder builder() {
return new AutoValue_Animal.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder setName(String value);
public abstract Builder setNumberOfLegs(int value);
// Option 1: Flexible setter
public abstract Builder setCountries(Set<String> value);
public abstract Builder setCountries(String... value);
// Option 2: Accumulation via internal builder (breaks chain)
abstract ImmutableSet.Builder<String> countriesBuilder();
// Option 3: Accumulation via helper (maintains chain)
public final Builder addCountry(String value) {
countriesBuilder().add(value);
return this;
}
public abstract Animal build();
}
}