hixhix
hixhix

Reputation: 791

How do you simulate a null safe operator with a default return value?

I'm sorry for the title but I cant find a good way to describe the problem in one sentence. In short, I have a lot of Java code following this pattern

if (obj != null && obj.getPropertyX() != null) {
    return obj.getPropertyX();
}
return defaultProperty;

which can be rewritten as

return obj != null && obj.getPropertyX() != null ? obj.getPropertyX() : defaultProperty;

It's still ugly and I'm wondering if there is some API in Google Guava or other library to help clean up this code. Specifically, I'm looking for something like

return someAPI(obj, "getPropertyX", defaultProperty);

I can implement this method using reflection but I'm not sure if that's the proper way to do it. Thanks.

Upvotes: 9

Views: 4441

Answers (1)

beny23
beny23

Reputation: 35038

In Java 8, you could use:

return Optional.ofNullable(obj).map(Obj::getPropertyX).orElse(defaultProperty);

Upvotes: 19

Related Questions