Optional<T> should have a fromNullable method

Ryan Bergman ryan.bergman at gmail.com
Fri Jan 4 17:10:09 PST 2013


Greetings Team Lambda,

   Forgive me if this is a re-hash. I looked back in the archives and could
not find anything about this specifically.

   I feel that Optional should have a static .fromNullable(T value) method.
Currently if you are building Optionals it probably means that some of
those optionals may not have values (that's why you are using it after
all).

Right now I would have to test for that manually:

   if(value == null){
         return Optional.empty();
    }
   return Optional.of(value);

Guava has this same method on its Optional class. I took a look at a large
project I work on that makes extensive use of Guava and found it used in
several places.

Thanks and Rock On!
Ryan Bergman

P.S. this is the only reference I could find on the subject:

<ricky.clarkson at gmail.com> wrote:
> For reference, Scala's Option allows Some(null), and that's largely
> considered to be a mistake and one that hampers any potential inlining of
> Option to straight references.  Functional Java's Option also allows
> some(null), but I doubt the maintainers allowed that deliberately.  Guava's
> Optional rejects Optional.of(null) with a NullPointerException.
>
> Although one could argue that Optional does not replace null, that is a
> very common use and rejecting possibly accidental nulls would be very
> helpful.
>


More information about the lambda-dev mailing list