Optional != @Nullable

Sam Pullara sam at sampullara.com
Sun Sep 30 12:54:04 PDT 2012


Nice. Just spelling it out a little:

    static String address(InetSocketAddress sa) {
        return elvis(elvis(sa, isa -> isa.getAddress()), ia -> ia.getHostAddress());
    }

    public static <T, V> V elvis(T t, Mapper<T, V> mapper) {
        return t == null ? null : mapper.map(t);
    }

Has the unfortunate property of being inverted. I'd probably rename elvis to 'option', 'nullOr', 'maybe' or something like that. I ended up using this kind of operation all over the place except it also did things like this:

    @SuppressWarnings("unchecked")
    public static <T> Iterable<T> elvis(Iterable<T> iterable) {
        return iterable == null ? empty : iterable; 
    }

Then you could do loops and fluent stuff without thinking about it.

        for (String s : elvis(strings)) {

        }
        stream(elvis(strings)).forEach((string) -> {

        });

I'm kind of liking the '___Or' naming now that I look at it. The first one would be nullOr the second one emptyOr. It does put all the responsibility on the caller though. Perhaps we could make the .stream() methods safer by doing it for you?

Sam

On Sep 30, 2012, at 12:28 PM, Zhong Yu <zhong.j.yu at gmail.com> wrote:

> On Sun, Sep 30, 2012 at 3:36 AM, Artur Biesiadowski <abies at adres.pl> wrote:
>> 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();
> 
> elvis(
>    elvis(
>        remoteAddress,
>        InetSocketAddress::getAddressA),
>    InetAddress::getHostAddress);
> 
> :D
> 
> 
>> 
>> ?
>> 
>> 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