java.util.Optional fields

Remi Forax forax at
Fri Sep 21 09:59:20 PDT 2012

On 09/21/2012 06:53 PM, Peter Levart wrote:
> On 09/21/2012 06:36 PM, Remi Forax wrote:
>> Now, to come back to Optional, Java has not a really good way to
>> currently deal with null,
>> Stephen Colebourne run several polls in 2009 [1] that shows that.
>> The real question is does Optional is the good answer.
>> There are several issues with Optional:
>>     - it introduces a cost at runtime (see one of my previous post that
>> explain why the
>>       VM will not remove it) that makes it useless as return value of
>> map.get() by example.
>>       So it's only a solution where the cost of creating an object is
>> hidden by the cost
>>       of doing the calculation in the loop.
>>     - Optional should implements all methods and do nothing,
>>       By example, users will want Optional to implement Iterable by
>> example to be able
>>       use Optional in a for-each, or implements Comparable, etc.
>>       Conceptually, Optional is a kind of kitchen sink but the type
>> system of Java will see it
>>       as an ordinary object. The last time we chose a similar idea, it
>> was when we decide
>>       to do the boxing using plain old Java classes instead of using 
>> type
>> known by the type system.
>>       As a result, we can't use primitive type in generics.
>>     - If Optional is introduced in java.util, we will see types like
>> List<Optional<T>>, i.e. types
>>       that embody Optional, something you don't want with @NotNull.
>> I might be wrong, but for me Optional doesn't worth the pain it will
>> introduce.
>> Rémi
>> [1]
> Those issues could be minimized by only allowing the Stream internal 
> machinery to construct instances of Optional (by making the 
> constructor package protected).
> This way it will only be used for the purpose of fluent API inside 
> Stream and people will not be tempted to construct own APIs with it.

No, this solve only the last bullet.

> Regards, Peter


More information about the lambda-dev mailing list