Chris Morris
Chris Morris

Reputation: 4444

how to clear an `AutoValue` property via an `AutoValue.Builder`

I have an AutoValue with an Optional property. The AutoValue also has a Builder. Is there a way to use the Builder to clear the Optional property? I could not find anything about it in the AutoValue.Builder documentation. If this is not possible, is there a suggested work around?

Example below:

package com.google.sandbox;

import com.google.auto.value.AutoValue;
import java.util.Optional;

@AutoValue
  public abstract static class MainMessage {

    public static Builder builder() {
      return new AutoValue_MainClass_MainMessage.Builder();
    }

    public abstract Optional<Integer> val();

    public abstract Builder toBuilder();

    /** Builder for MainMessage. */
    @AutoValue.Builder
    public abstract static class Builder {

      public abstract Builder setVal(int value);

      public abstract Builder clearVal(); // This causes a compiler error.

      public abstract MainMessage build();
    }
  }

Error:

[AutoValueBuilderNoArg] Method without arguments should be a build method returning com.google.sandbox.MainClass.MainMessage, or a getter method with the same name and type as a property method of com.google.sandbox.MainClass.MainMessage, or fooBuilder() where foo() or getFoo() is a property method of com.google.sandbox.MainClass.MainMessage
      public abstract Builder clearVal();

Upvotes: 0

Views: 527

Answers (1)

emcmanus
emcmanus

Reputation: 363

You can define a second setVal method with an Optional<Integer> parameter, then call that with Optional.empty(). If you don't want that to be part of the public API, you could make it package-private and have a public method that calls it:

  public abstract static class Builder {
    public abstract Builder setVal(int value);
    abstract Builder setVal(Optional<Integer> value);
    public Builder clearVal() {
      setVal(Optional.empty());
    }
    public abstract MainMessage build();
  }

Upvotes: 2

Related Questions