Robert Munteanu created SLING-8758:
--------------------------------------

             Summary: Add Adaptable method with a non-null return value
                 Key: SLING-8758
                 URL: https://issues.apache.org/jira/browse/SLING-8758
             Project: Sling
          Issue Type: Improvement
          Components: API
            Reporter: Robert Munteanu
             Fix For: API 2.20.2


We have had long-standing discussions about the fact that {{adaptTo}} returning 
null can lead to many hard-to-trace bugs.

One option of evolving the API is to add a default method to the adaptable 
which returns an optional

{code:java}
    default @NotNull <AdapterType> Optional<AdapterType> tryAdapt(@NotNull 
Class<AdapterType> type) {
        return Optional.ofNullable(adaptTo(type));
    }
{code}

This can in turn be used by clients to check that the adaption succeeed in a 
more fluent way
{code:java}
MyAdapted resource = resource.tryAdapt(MyAdapted.class)
            .orElseThrow( () -> new RuntimeException("Adaption failed") )
            .get();{code}

or enable functional API usage patterns

{code:java}
MyAdapted resource = resource.tryAdapt(MyAdapted.class)
        .ifPresent( a ->  consume(a) );
{code}





--
This message was sent by Atlassian Jira
(v8.3.4#803005)

Reply via email to