英文:
returning early from a method if an Optional is empty
问题
以下是您要求的翻译内容:
是否有一种比这个更有效的方式从一个方法中提前返回,如果一个 Optional 是空的呢?
public boolean validate(Optional<Object> obj) {
if (obj.isPresent(obj)) {
var object = obj.get();
// 对 object 做一些操作
return true;
} else {
return false;
}
}
我寻找的是像 Optional.ifPresentOrElse 这样的东西,但在这种情况下我不能使用它,因为它接受的 lambda 参数(Consumer 和 Runnable)都具有 void 返回类型。
如果 lambda 参数的类型改为 Function,并且 ifPresentOrElse 的返回值是调用的 lambda 的返回值,我可以这样做:
public boolean validate(Optional<Object> obj) {
return obj.ifPresentOrElse(
object -> {
// 对 object 做一些操作
return true;
},
() -> false
);
}
但是在 Optional API 中似乎没有类似这样的东西。从函数式的角度来看,是否有改进第一个示例的方法呢?
英文:
Is there a more functional way to return early from a method if an Optional is empty than this?
public boolean validate(Optional<Object> obj) {
if (obj.isPresent(obj) {
var object = obj.get();
// do something with the object
return true
} else {
return false;
}
}
What I'm looking for is something like Optional.ifPresentOrElse, but I can't use that in this case, because the lambda arguments it takes (Consumer and Runnable) both have void return types.
If the lambda arguments were instead of type Function, and the return value of ifPresentOrElse is whatever the invoked lambda returns, I could do this instead
public boolean validate(Optional<Object> obj) {
return obj.ifPresentOrElse(
object -> {
// do something with the object
return true;
},
() -> false
);
}
But there doesn't seem to be anything like this in the Optional API. Is there a way to improve upon the first example from a functional point-of-view?
答案1
得分: 4
你可以使用map和orElse的组合,就像下面这样:
obj.map(o -> true).orElse(false);
在map中,你可以执行// 对对象进行一些操作,然后决定是否返回true。
英文:
You can use a combination of map and orElse like the following :
obj.map(o->true).orElse(false);
inside the map you can // do something with the object and decide whether to return true or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论