elseCondition当前抛出空值时是否可以在一行中写nullPointer
在我的场景中,returnValue是一个String,它为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() {...}
}
Run Code Online (Sandbox Code Playgroud)
elseCondition还应该用包裹Optional:
Optional.ofNullable(returnValue)
.orElse(Optional.ofNullable(elseCondition)
.map(ElseCodnition::getValue)
.orElse(null));
Run Code Online (Sandbox Code Playgroud)
也就是说,我不确定这是Optionals的好用例。
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |