java orelse,可选orElse Java中的可选项

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"

Consider the following pattern:

Optional resultFromServiceA = serviceA(args);

if (resultFromServiceA.isPresent) return result;

else {

Optional resultFromServiceB = serviceB(args);

if (resultFromServiceB.isPresent) return resultFromServiceB;

else return serviceC(args);

}

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 orElse(Supplier> otherSupplier) {

return value != null ? this : other.get();

}

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.

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.

解决方案

This is part of JDK 9 in the form of or, which takes a Supplier>. Your example would then be:

return serviceA(args)

.or(() -> serviceB(args))

.or(() -> serviceC(args));

For details see the Javadoc or this post I wrote.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值