当elseCondition
当前为空时,是否可能在一行中抛出nullPointer
在我的场景中,returnValue是一个字符串,它为null。
我要写的条件是
if (returnValue != null) {
return returnValue;
} else if (elseCondition != null) {
return elseCondition.getValue();
} else {
return null;
}
Optional.ofNullable(returnValue).orElse(elseCondition.getValue()) //throws nullPointer as elseCondition is null
class ElseCodnition {
private String value;
getValue() {...}
}
答案 0 :(得分:5)
elseCondition
也应该用Optional
包装:
Optional.ofNullable(returnValue)
.orElse(Optional.ofNullable(elseCondition)
.map(ElseCodnition::getValue)
.orElse(null));
也就是说,我不确定这是Optional
的好用例。
答案 1 :(得分:1)
我最好将三元运算符用作:
return (returnValue != null) ? returnValue :
((elseCondition != null) ? elseCondition.getValue() : null);
将条件分支模制成链接的Optional
听起来并不好。
答案 2 :(得分:0)
对于Optional
来说肯定不是工作,相反,您可以创建一个避免NPE的调用对象获取方法的方法:
static <T, R> R applyIfNotNull(T obj, Function<T, R> function) {
return obj != null ? function.apply(obj) : null;
}
和用例
return returnValue != null ? returnValue : applyIfNotNull(elseCondition, ElseCondition::getValue);