You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@sling.apache.org by Jörg Hoh <jh...@googlemail.com.INVALID> on 2018/11/12 13:21:50 UTC

adaptTo() should return an Optional

Hi,

When working in a more functional style, the null checks for adaptTo() are
not rally nice, and I typically wrap the result of adaptTo() just into an
Optional by my own.

String propValue =
Optional.ofNullable(resource.adaptTo(ValueMap.class)).map(vm ->
vm.get("property").orElse(() -> {return "defaultValue"});

it would be nice if I could write it like this:

String propValue = resource.adaptTo(ValueMap.class).map(vm ->
vm.get("property").orElse(() -> {return "defaultValue")});

It would require an extension to the Adaptable interface, but that could be
implemented as default method, so it's signature would not change.
While I can do that in my code as well, it would be good to have it in the
Adaptable interface as well; it can encourage others to use Optional
instead of explicit Null Checks; and the Null checks are often missing :-(

WDYT?


-- 
Cheers,
Jörg Hoh,

http://cqdump.wordpress.com
Twitter: @joerghoh

Re: adaptTo() should return an Optional

Posted by Carsten Ziegeler <cz...@apache.org>.
Use resource.getValueMap() :)

Regards
Carsten

Am 12.11.2018 um 14:21 schrieb Jörg Hoh:
> Hi,
> 
> When working in a more functional style, the null checks for adaptTo() are
> not rally nice, and I typically wrap the result of adaptTo() just into an
> Optional by my own.
> 
> String propValue =
> Optional.ofNullable(resource.adaptTo(ValueMap.class)).map(vm ->
> vm.get("property").orElse(() -> {return "defaultValue"});
> 
> it would be nice if I could write it like this:
> 
> String propValue = resource.adaptTo(ValueMap.class).map(vm ->
> vm.get("property").orElse(() -> {return "defaultValue")});
> 
> It would require an extension to the Adaptable interface, but that could be
> implemented as default method, so it's signature would not change.
> While I can do that in my code as well, it would be good to have it in the
> Adaptable interface as well; it can encourage others to use Optional
> instead of explicit Null Checks; and the Null checks are often missing :-(
> 
> WDYT?
> 
> 

-- 
Carsten Ziegeler
Adobe Research Switzerland
cziegeler@apache.org