Scala 中的条件未来 [英] Conditional Future in Scala

查看:46
本文介绍了Scala 中的条件未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这两个期货,我只需要在条件为真时运行第一个(参见 if y>2).但是我得到一个异常Future.filter 谓词不满足.这是什么意思以及如何修复示例?

Given these two futures, I need to run the first one only if a condition is true (see if y>2). But I get an exception Future.filter predicate is not satisfied. What does this mean and how to fix the example?

object TestFutures extends App {

  val f1 = Future {
    1
  }

  val f2 = Future {
    2
  }

  val y = 1

  val x = for {
    x1 <- f1 if y>2
    x2 <- f2
  }  yield x1 + x2


  Thread.sleep(5000)
  println(x)
}

推荐答案

filter 并不是你应该能够在 Future 上做的事情 - <没有通过条件返回的code>Future?从你的例子来看:我们仍然需要有一个 x1 的值(即使它失败了 if)以在 yield x1 + x2 中使用.

filter is not really something you should be able to do on a Future - what would a Future that didn't pass the condition return? From your example: we still need to have a value for x1 (even if it fails the if) to use in the yield x1 + x2.

因此,Future 上的 filter 方法被设计为当谓词评估为假时很难失败.这是一种断言".您可能更喜欢这样的东西(如果条件失败,它为 x1 提供默认值):

Therefore, the filter method on Future is designed to fail hard when the predicate evaluates to false. It is an "assert" of sorts. You probably would prefer something like this (that provides a default value for x1 if the condition fails):

val x = for {
  x1 <- if (y > 2) f1 else Future.successful(/* some-default-value-for-x1 */)
  x2 <- f2
}  yield x1 + x2

这篇关于Scala 中的条件未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆