可选orElse Java中的可选项 [英] Optional orElse Optional in Java
问题描述
我一直在使用新的可选类型在Java 8中,我遇到了一个似乎是功能上不支持的常见操作:orElseOptional
I've been working with the new Optional type in Java 8, and I've come across what seems like a common operation that isn't supported functionally: an "orElseOptional"
考虑以下模式:
Optional<Result> resultFromServiceA = serviceA(args);
if (resultFromServiceA.isPresent) return result;
else {
Optional<Result> resultFromServiceB = serviceB(args);
if (resultFromServiceB.isPresent) return resultFromServiceB;
else return serviceC(args);
}
这种模式有很多种形式,但归结为想要 orElse在一个可选项上,它接受一个生成一个新的可选项的函数,仅当当前的函数不存在时调用。
There are many forms of this pattern, but it boils down to wanting an "orElse" on an optional that takes a function producing a new optional, called only if the current one does not exist.
它的实现看起来像这样:
It's implementation would look like this:
public Optional<T> orElse(Supplier<Optional<? extends T>> otherSupplier) {
return value != null ? this : other.get();
}
我很好奇是否有这样的方法不存在的原因,如果我只是以一种无意的方式使用Optional,以及人们如何处理这种情况的其他方式。
I'm curious if there's a reason such a method doesn't exist, if I'm just using Optional in an unintended way, and what other ways people have come up with to deal with this case.
我应该说我认为解决方案涉及自定义实用程序类/方法并不优雅,因为使用我的代码的人不一定知道它们存在。
I should say that I think that solutions involving custom utility classes/methods aren't elegant because people working with my code won't necessarily know they exist.
另外,如果有人知道,这样的方法是不是包含在JDK 9中,我可以在哪里提出这样的方法?对我来说这似乎是一个非常明显的遗漏。
Also, if anyone knows, will such a method be included in JDK 9, and where might I propose such a method? This seems like a pretty glaring omission to the API to me.
推荐答案
这是JDK 9的一部分,形式为或
,需要供应商< Optional< T>>
。那么你的例子是:
This is part of JDK 9 in the form of or
, which takes a Supplier<Optional<T>>
. Your example would then be:
return serviceA(args)
.or(() -> serviceB(args))
.or(() -> serviceC(args));
这篇关于可选orElse Java中的可选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!