java.util.Optional fields

Kevin Bourrillion kevinb at google.com
Fri Sep 21 08:20:10 PDT 2012


On Fri, Sep 21, 2012 at 8:05 AM, Peter Levart <peter.levart at gmail.com>wrote:

The 3-state Optional (non-null value, null value, empty) has a benefit
> in that it can express the 3rd option in a way that does not force using
> exceptions.
>

That is correct.

- A plain old T reference has only one kind of not-there: null.
- A Guava Optional<T> reference has two: null, and absent.
- The proposed Optional<T> has three: null, absent, and contains-null.

If this is an improvement, why not four?  Of course, that's ridiculous.  So
we're really suggesting that three is somehow the magic number of logical
kinds of "not-there" that should be enabled?

And what of all the users who only wanted two?  One kind of not-there will
be represented as Optional.absent() for sure, but the other could be either
plain null or optional-containing-null, and neither approach is obviously
better than the other, so users will probably end up using a mixture.

Result: proper usage of this Optional will really depend on JSR-308
annotations.  To get the behavior Guava gives them today, users will need
to use Optional<@Nonnull T>.

Guava's been getting along fine with its Optional that can't hold null.
When users have three kinds of not-there, we suggest that they're
*really* better
off making their own type that actually defines what each of these is
really supposed to *mean* more clearly.


More information about the lambda-dev mailing list