java8 orElse(null.getValue())如何处理

时间:2019-04-15 05:50:45

标签: java java-8

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() {...}
}

3 个答案:

答案 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);