Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

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.

like image 288
hixhix Avatar asked Oct 28 '15 23:10

hixhix


People also ask

What is a null safe operator?

Null-safe operator is a new syntax in PHP 8.0, that provides optional chaining feature to PHP. The null-safe operator allows reading the value of property and method return value chaining, where the null-safe operator short-circuits the retrieval if the value is null , without causing any errors.

What is Elvis operator TypeScript?

In certain computer programming languages, the Elvis operator, often written ?: , or or || , is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is identical to a short-circuit or with "last value" semantics.

What is safe operator in angular?

The Angular safe navigation operator, ? , guards against null and undefined values in property paths. Here, it protects against a view render failure if item is null .

What is the purpose of the safe navigation operator?

It is used to avoid sequential explicit null checks and assignments and replace them with method/property chaining.


1 Answers

In Java 8, you could use:

return Optional.ofNullable(obj).map(Obj::getPropertyX).orElse(defaultProperty);
like image 137
beny23 Avatar answered Oct 23 '22 10:10

beny23