Optional fromNullable()
Ali Ebrahimi
ali.ebrahimi1781 at gmail.com
Fri Apr 26 02:20:37 PDT 2013
I don't think null value equals not a value.
consider database example:
db.query(" select name from Employee where id = " + 10);
here, name maybe null or no employee with id = 10
Ali Ebrahimi
On Fri, Apr 26, 2013 at 1:05 PM, Michael Hixson <michael.hixson at gmail.com>wrote:
> First, I'll venture to say that debates about Optional took up way
> more time than they were worth, and your reasonable suggestion may be
> met with silence. But I had the same reaction initially, so I'll join
> in.
>
> This has extremely low utility because it can be done with a trivial
> method in your own code:
>
> public static <T> Optional<T> fromNullable(T object) {
> return (object == null) ? Optional.empty() : Optional.of(object);
> }
>
> Your implementation will be just as good as the JDK's theoretical
> implementation. There are no tricks. It's simple. Write it once,
> it's good forever.
>
> That said, I don't understand why Optional.of doesn't have this
> behavior itself. That is, I don't understand why Optional.of(null)
> throws instead of returning Optional.empty(). The current
> implementation stands in a weird middle ground of hand-holdiness: it
> doesn't want to provide you with the obvious solution of converting
> nullable references to Optionals because you should do that yourself,
> it doesn't want you to toss around nulls carelessly so it throws NPE
> on Optional.of(null), even though it suspiciously accepts null
> arguments to orElse, and it doesn't trust that users who think about
> null would do Optional.of(Objects.requireNonNull(object)). There's a
> peculiar, focused behavior there. The JDK is on safe ground offering
> Optional.of with Guava's behavior because it's been battle-tested, but
> it sure is confusing to me.
>
> -Michael
>
> On Fri, Apr 26, 2013 at 12:30 AM, Seibt, Volker
> <volker.seibt at buenting.de> wrote:
> > In contrast to the Guava API Optional class in Java contains no static
> method "fromNullable()" which allows null-values and analogous should
> deliver Optional.empty() in this case.
> >
> > It seems to be very comfortable in later "Optionalizing" return values
> like e.g.
> >
> > Optional<T> o = Optional.fromNullable(map.get(key));
> >
> > instead of
> >
> > Optional<T> o = map.get(key) == null ? Optional.empty() :
> Optional.of(map(key));
> >
> > or worse readable
> >
> > T t = map.get(key);
> > Optional<T> o = t == null ? Optional.empty() : Optional.of(t);
> >
> > to avoid calling map(..) twice.
> >
> >
> > Is there a reason why it's omitted?
> >
> >
>
>
More information about the lambda-dev
mailing list