Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.
ObjectUtils.firstNonNull(T...) from Apache Commons Lang 3 is another option. I prefer this because, unlike Guava, this method does not throw an Exception. It will simply return null.
No, and be aware that workaround functions are not exactly the same, a true null coalescing operator short circuits like && and || do, meaning it will only attempt to evaluate the second expression if the first is null.
发布评论
评论(5)
可悲的是 - 没有。您可以做的最接近的是:
当然,如果您觉得有必要,您可以将其包装在库方法中(不太可能减少太多长度),但在语法级别上没有任何更简洁的可用方法。
Sadly - no. The closest you can do is:
Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.
Guava 库有一个方法可以执行类似的操作,称为 MoreObjects.firstNonNull(T,T)。
当您有类似的情况时,这会更有帮助,
因为它可以使您免于两次调用可能昂贵的方法或在代码中声明一个局部变量来引用两次。
The Guava library has a method that does something similar called MoreObjects.firstNonNull(T,T).
This is more helpful when you have something like
since it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.
简短的回答:否
您能做的最好的事情就是创建一个静态实用方法(以便可以使用
import static
语法导入它)上面相当于Guava的方法< code>firstNonNull by @ColinD,但一般来说可以扩展更多
Short answer: no
The best you can do is to create a static utility method (so that it can be imported using
import static
syntax)The above is equivalent to Guava's method
firstNonNull
by @ColinD, but that can be extended more in generalObjectUtils.firstNonNull(T...)
是另一种选择。我更喜欢这个,因为与 Guava 不同,这个方法不会抛出Exception
。它只会返回null
。ObjectUtils.firstNonNull(T...)
from Apache Commons Lang 3 is another option. I prefer this because, unlike Guava, this method does not throw anException
. It will simply returnnull
.不,请注意,解决方法函数并不完全相同,真正的空合并运算符短路,如 &&和 || do,这意味着如果第一个表达式为空,它只会尝试计算第二个表达式。
No, and be aware that workaround functions are not exactly the same, a true null coalescing operator short circuits like && and || do, meaning it will only attempt to evaluate the second expression if the first is null.