spakai
spakai

Reputation: 303

java Optional checking nulls

I was under the impression Optional.ofNullable(response.getSubscriber()) can also determine if the object response is null, but it can't

Is there a better way to check that response and response.getSubscriber is present ?

  public Subscriber generateSubscriber(SPRGetSubscriberResponse response) {
        if (response != null) {
            Optional<SPRSubscriber> option = Optional.ofNullable(response.getSubscriber());
            if (option.isPresent()) {
                Subscriber subscriber = new Subscriber();
                //...copy members from response to subscriber

                return subscriber;
            }
        }
        return null;
    }

Upvotes: 0

Views: 178

Answers (1)

You're mixing conditionals and Optional in a way that gets all of the clumsiness and none of the fluency. To use just the basic features, no Optional:

if (response != null && response.getSubscriber != null)

In Groovy:

response?.subscriber // null-safe navigation to collapse your conditional

With Java 8 goodness:

return Optional.ofNullable(response)
    .map(SPRGetSubscriberResponse::getSubscriber)
    .map(original -> { /* return the copied version */ })
    .orElse(null);

Upvotes: 2

Related Questions