Loose ends: Optional
brian.goetz at oracle.com
Mon Jun 10 08:46:36 PDT 2013
>> Now, the same can be superficially said of map/flatMap -- people can
>> easily write these themselves too -- but there is a key difference;
> With the method map you propose, instead of
> (foo() == null ? O.empty() : O.of(o))
> you can write
> O.of("unused").map(unused -> foo())
> which is ugly but more fluent.
> So fluency is nice but it should never trump the semantics.
I think you've missed the point here. The putative fluency benefit is
being able to chain operations off of Optional returns from the *end* of
the chain. The above does not speak to that.
>> People want flatMap not because it offers functionality people can't
>> write for themselves, but that they can't otherwise do it fluently at
>> the end of a chain.
> yes, the question is more. Why do they need flatMap ?
I think this is well-covered ground; I think you should review the
discussion that I linked to earlier.
>> So, I would amend your statement to: if we add map/flatMap, we then
>> have to ask the question of whether we should also add ofNullable.
> Yes, map can take a method that return null and flatMap can not be used
> with a method that returns null instead of Optional.
> That's the issue.
> As I said, the issue is not exactly if we add map/flatMap, but more how
> we deal with null in map().
Yes, I think this is the only real remaining issue that isn't simply
"taste". So let's restrict discussion to this issue.
For flatMap, the rationale for "throw on null return" here is that:
Optional-returning methods should never return null (they should be
total functions, they can always return either a present or empty
optional), so a null return should be considered a programming error
(like trying to unbox the "null" Integer.)
For map, it is different; it is entirely reasonable to imagine that the
mapper is a partial function, so, just like with computeIfAbsent, we
should interpret a null return as "no result".
More information about the lambda-libs-spec-observers