从方法中提前返回,如果Optional为空。

huangapple go评论59阅读模式
英文:

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 参数(ConsumerRunnable)都具有 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&lt;Object&gt; 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&lt;Object&gt; obj) {

  return obj.ifPresentOrElse(
    object -&gt; {
      // do something with the object
      return true;
    }, 
    () -&gt; 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

你可以使用maporElse的组合,就像下面这样:

obj.map(o -> true).orElse(false);

map中,你可以执行// 对对象进行一些操作,然后决定是否返回true。

英文:

You can use a combination of map and orElse like the following :

obj.map(o-&gt;true).orElse(false);

inside the map you can // do something with the object and decide whether to return true or not.

huangapple
  • 本文由 发表于 2020年8月26日 18:03:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63595248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定