Skip to content

Optional<T> should be Optional<T extends Object> #666

@cbracken

Description

@cbracken

Optional is intended as a substitute for non-nullable values. Ideally, it should have a generic type of T extends Object in order to prevent non-sensical declarations like Optional<Foo?>. Such declarations are unlikely to happen intentionally, but one could imagine the case of an Optional used in another generic class, where T is a nullable type.

Ideally, we should prevent such uses by declaring Optional as Optional<T extends Object>.

This is a potentially significant breaking change, since currently T implicitly extends dynamic and therefore checks like the following don't produce any analysis errors:

if (obj is Optional) {
  return obj.value.someMethod();
}

where someMethod is a method defined on T. All such call sites would need to be fixed up to obj is Optional<AppropriateType>.

A survey of the Google codebase suggests this would be a fairly extensive breaking change. Given that Optional makes little sense once null-safety is enabled in the language by default, the simpler change may simply be to leave as-is and deprecate the class once null-safety lands in the language.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions