Skip to content

No way to set Optional Property of type T to Optional.empty() #384

@mearly87

Description

@mearly87

If an optional property has been set, there is no way to set it back to Optional.empty() because the setter uses Optional.of() instead of Optional.ofNullable()

For example if you have this class:

import com.google.auto.value.AutoValue;
import java.util.Optional;
import javax.annotation.Nullable;

public class Test {

  @AutoValue
  public static abstract class Item {

    public abstract Optional<String> getName();

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

    public abstract Builder toBuilder();

    @AutoValue.Builder
    public static abstract class Builder {

      public abstract Builder setName(@Nullable String name);
      public abstract Item build();

    }
  }

  public static void main(String args[]) {
    Item item = Item.builder().setName("Test").build();
    item.toBuilder().setName(null).build();
  }
}

This will result in a NullPointerException. Is there no way to set this property to empty in the builder? Seems like a valid use case to me.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions