scala - Future中的 bool 逻辑[Boolean]

标签 scala future boolean-logic

在非并发编程中,我们通常有这种 bool 逻辑:

boolean canIMarryher(){
    return iLoveHer() && myParentsLoveHer() && shesHot() && sheSaidYes();
}

我的问题来了,如果所有这些(或其中一些条件)都是 Scala 中的 Future[Boolean] 呢?我还能像上面的例子一样得到一个清晰的方法吗?

更新
如您所知,在运行时的 bool 逻辑中,我们将进行“优化”,例如:使用 && 时立即返回并遇到了一个 false或使用 ||遇到了一个true .我也可以在 Future[Boolean] 中使用它吗?

问候,
德鲁

最佳答案

其他带有 for-comprehension 和 reduce 的答案不会“短路”。也就是说,如果第一个 future 需要一段时间才能完成,即使第二个 future 评估 false,我们也会等待整个时间。立即地。

澄清一下,这与传统 bool 逻辑中的短路不同,在传统 bool 逻辑中,我们按名称评估运算符的右侧。相反,目标是尽快产生答案。我们立即开始每个 future 的计算,并在结果出现时尽可能短路。在最好的情况下,我们只需要等待最快的 future,在最坏的情况下,我们必须等待最慢的 future。

这是一种支持这种类型短路的方法:

def all(futures: Future[Boolean]*)(implicit executor: ExecutionContext): Future[Boolean] = {
  Future.find(futures) { !_ } map { _.isEmpty }
}

def canIMarryher = all(iLoveHer, myParentsLoveHer, shesHot, sheSaidYes)

如果你真的想,你可以更进一步地定义&&和|| Future[Boolean] 的方法

关于scala - Future中的 bool 逻辑[Boolean],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32414803/

相关文章:

Python `or` , `and` 运算符优先级示例

boolean 代数简化

scala - Spark exitCode : 12 mean? 是什么意思

scala - Scala "extractor"可以在 unapply 上使用泛型吗?

r - 出现错误时如何停止并行循环

asynchronous - 我应该为 Future<void> 函数返回一个值吗?

javascript - JavaScript 中的 Deferred、Promise 和 Future 有什么区别?

scheme - 你如何在 Scheme 中表达 bool 否定?

scala - 升级到1.2版本后,将Marshaller的 future 未纳入隐含范围

scala - 为什么 PrefixMap++ PrefixMap 变得可变。Map