Optional != @Nullable

François Sarradin fsarradin at gmail.com
Sun Sep 30 03:24:47 PDT 2012

Hi Artur,

Indeed, for the traversing problem, the elvis operator is more
readable. But I think there are circumstances where flatMap solves
problems that elvis operator doesn't. Suppose you have two methods
getOptionalValue1 and getOptionalValue2. Both return an

Optional<Integer> result = getOptionalValue1().flatMap(
    x -> getOptionalValue2().flatMap(
        y -> optional(x * y)));
return result.getOrElse(defaultValue);

The nice thing here is that you have a safe access both by what is
returned by getOptionalValue1 and getOptionalValue2.

Notice that if you have no flatMap operation, there is another nicer
solution. Suppose that Optional implements Iterable. You can express
the previous expression like this:

int result = defaultValue;
for (int x : getOptionalValue1()) {
    for (int y : getOptionalValue2()) {
        result = x * y;
return result;

Here, I use the for loop to destructure two Optionals... And Java does
it naturally and safely! So you can execute the inner operation
without fear of NPE, assuming Optional doesn't consider null as a
possible value.

And if you don't have no flatMap nor Optional implementing Iterable,
you can emulate flatMap by using map operation on an Optional of
Optional. But it is uglier.

François Sarradin

2012/9/30 Artur Biesiadowski <abies at adres.pl>:
> On 30/09/2012 10:13, Jed Wesley-Smith wrote:
>> Option<String> address(Session session) {
>>    return optional(
>>      session.getIoSession().getRemoteAddress()
>>    ).flatMap(socketAddress -> optional(socketAddress.getAddress())
>>    ).flatMap(inetAddress -> optional(inetAddress.getHostAddress()));
>> }
> Is it really more readable than
> return session.getIoSession().getRemoteAddress().?getAddress().?getHostAddress();
> ?
> Given java history and existing libraries, I think that repurposing null
> as None, assuming non-null contents of collections for most of
> lambda-empowered libraries/utilities and providing few operators for
> safe traversal (?. and ?: at least) would be a lot more useful solution.
> Regards,
> Artur Biesiadowski

More information about the lambda-dev mailing list