RFR : JDK-8001642 : Add Optional<T>, OptionalDouble, OptionalInt, OptionalLong

Remi Forax forax at univ-mlv.fr
Wed Mar 6 01:47:56 PST 2013

Ok, let be nuclear on this,
There is no good reason to introduce Optional<T> in java.util.

It doen't work like Google's Guava Optional despite having the same 
name, it doesn't work like Scala's Option despite having a similar name, 
moreover the lambda pipeline face a similar issue with the design of 
collectors (see stream.collect()) but solve that similar problem with a 
different design, so the design of Optional is not even consistent with 
the rest of the stream API.

So why do we want something like Optional, we want it to be able to 
represent the fact that as Mike states a returning result can have no 
value by example Colections.emptyList().stream().findFirst() should 
'return' no value.

As Stephen Colebourne said, Optional is a bad name because Scala uses 
Option [1] which can used in the same context, as result of a filter/map 
etc. but Option in Scala is a way to mask null. Given the name 
proximity, people will start to use Optional like Option in Scala and we 
will see methods returning things like Optional<List<Optional<String>>>.

Google's Guava, which is a popular library, defines a class named 
Optional, but allow to store null unlike the current proposed 
implementation, this will generate a lot of confusions and frustrations.

In fact, we don't need Optional at all, because we don't need to return 
a value that can represent a value or no value,
the idea is that methods like findFirst should take a lambda as 
parameter letting the user to decide what value should be returned by 
findFirst if there is a value and if there is no value.
So instead of
you will write
with orNull() defined as like that
   public static <T> Optionalizer orNull() {
     return (isPresent, element) -> isPresent? element: null;

The whole design is explained here [2] and is similar to the way 
Collectors are defined [3],
it's basically the lambda way of thinking, instead of creating an object 
representing the different states resulting of a call to findFirst,
findFirst takes a lambda as parameter which is fed with the states of a 


[1] http://www.scala-lang.org/api/current/index.html#scala.Option

On 03/04/2013 09:29 PM, Mike Duigou wrote:
> Hello All;
> This patch introduces Optional container objects to be used by the lambda streams libraries for returning results.
> The reference Optional type, as defined, intentionally does not allow null values. null may be used with the Optional.orElse() method.
> All of the Optional types define hashCode() and equals implementations. Use of Optional types in collections should be generally discouraged but having useful equals() and hashCode() is ever so convenient.
> http://cr.openjdk.java.net/~mduigou/JDK-8001642/0/webrev/
> Mike

More information about the lambda-libs-spec-experts mailing list