如何在Java 8中实现Elvis运算符? [英] How to implement the Elvis operator in Java 8?
问题描述
我有一个经典的猫王运算符"案例,我在其中调用每个可能返回null并将它们链接在一起的方法:
I have the classic "Elvis operator" case, where I'm calling methods that each may return null and chaining them together:
thing?:nullableMethod1(a)?:nullableMethod2(b)?:nullableMethod3()
在Java 8中,我发现的最可靠的实现是这样的:
In Java 8, the most faithful implementation I've found is something like this:
return Optional.ofNullable(thing)
.flatMap(x -> Optional.ofNullable(x.nullableMethod1(a)))
.flatMap(y -> Optional.ofNullable(y.nullableMethod2(b)))
.flatMap(z -> Optional.ofNullable(z.nullableMethod3()))
我希望Java的Optional
与elvis运算符类似:
I wish that Java's Optional
had something akin to the elvis operator:
public<U> Optional<U> elvisOperator(Function<? super T, ? extends U> mapper) {
return flatMap(t -> Optional.ofNullable(mapper.apply(t));
}
这样我就不必包装每个返回值:
So that I wouldn't have to wrap each return value:
return Optional.ofNullable(thing)
.elvisOperator(x -> x.nullableMethod1(a))
.elvisOperator(y -> y.nullableMethod2(b))
.elvisOperator(Z::nullableMethod3); // also nice
在Java 8中是否有更高效,更惯用的方式实现Elvis运算符模式?
Is there a more efficient and idiomatic way to implement the Elvis operator pattern in Java 8?
推荐答案
也许我正在忽略某些内容,但是是否有不能使用Optional#map
的原因呢?
Maybe I'm overlooking something, but is there a reason that you can't use Optional#map
?
以下示例不打印任何内容,因为Optional
是短路,也就是说,如果Optional
内部的值不存在(它是null
或
The following example prints nothing, as Optional
is short-circuiting in the sense that, if the value inside the Optional
doesn't exist (it's null
or the Optional
is empty), it's treated as empty.
Optional.ofNullable("test")
.map(s -> null)
.ifPresent(System.out::println);
基于这个原因,我认为您可以执行以下操作:
For that reason, I'd think you could just do the following:
return Optional.ofNullable(thing)
.map(x -> x.nullableMethod1(a))
.map(y -> y.nullableMethod2(b))
.map(Z::nullableMethod3);
这将映射您的thing
(如果存在),否则返回一个空的Optional
.
This would map your thing
if it exists, or return an empty Optional
otherwise.
这篇关于如何在Java 8中实现Elvis运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!