关于Optional
API的问题和线程太多,但我的情况没有找到任何问题。
例如,为了记录目的,我首先需要检查Optional
变量的空度,然后检查该值(如果存在)和一些谓词。无论检查失败,我都需要抛出异常。
下面是我真正的解决方法
SomeValue value = someOptional.orElseThrow(() -> {
log.debug("nothing here");
return new NothingSpecialHereException();
});
if (!value.isSpecial()) {
log.debug("something here, but not special");
throw new NothingSpecialHereException();
}
[当我正在寻找替代解决方案时,我尝试了类似的方法
SomeValue value = someOptional
.filter(SomeValue::isSpecial)
.orElseThrow(() -> {
log.debug("nothing special here"); // but this case for both "no value" and "value is not special"
return new NothingSpecialHereException();
});
我知道在Java中没有针对这种情况的内置解决方案,但似乎我缺少以下内容:
SomeValue value = someOptional
.ifNotPresent(() -> log.debug("nothing here")) // that method returns Optional for further invocatons
.filter(val -> {
if (!val.isSpecial()) {
log.debug("something here, but not special");
return false;
}
return true;
})
.orElseThrow(NothingSpecialHereException::new);
[这不是我第一次错过在管道中间而不是末端使用ifNotPresent
或else*
之类的方法。 IMO有时这种方法可能更具可读性,例如
optional
.map(...)
.filter(...)
.ifEmpty(...) // do smth after filter, maybe even throw
.map(...) // and continue processing
也许有人遇到相同的问题?还是我错过了一些更好的解决方案?也许有一个图书馆为此提供解决方案?
JDK Optional
包括(仅从Java 9开始,这是Java 8中的主要疏忽)ifPresentOrElse
,可以将其与no-op first参数一起使用。另外,Vavr库是一组比Optional
更加一致的功能性包装,并以具有额外依赖性的代价提供了其他有用的包装,例如Try
。