Scala:理解期货的条件

Scala:理解期货的条件,scala,future,for-comprehension,Scala,Future,For Comprehension,对于理解,我需要一个,它调用N个方法,这些方法返回一个Future[Int],并且只产生奇数。以下代码不起作用,因为在第一个偶数结果之后,块返回一个失败: import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global def f1 = Future(1) def f2 = Future(2) def f3 = Future(3) def f4 = Future(4) for {

对于理解,我需要一个
,它调用N个方法,这些方法返回一个
Future[Int]
,并且只产生奇数。以下代码不起作用,因为在第一个偶数结果之后,块返回一个
失败

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def f1 = Future(1)
def f2 = Future(2)
def f3 = Future(3)
def f4 = Future(4)

for {
  i1 <- f1 if i1 % 2 != 0
  i2 <- f2 if i2 % 2 != 0
  i3 <- f3 if i3 % 2 != 0
  i4 <- f4 if i4 % 2 != 0
} yield ???

像这样的东西行吗

val futures = List(f1, f2, f3, f4)
Future.sequence(futures).map(_.filter(_ % 2 != 0))
结果是

List(1, 3)

像这样的东西行吗

val futures = List(f1, f2, f3, f4)
Future.sequence(futures).map(_.filter(_ % 2 != 0))
结果是

List(1, 3)

是否可以避免过滤?在我的实际用例中,列表可能相当长……编译器将
if
中的
条件转化为过滤器(实际上是
with filter()
)。是否可以避免过滤?在我的实际用例中,列表可能相当长……编译器将
if
中的
条件转化为一个过滤器(实际上是
withFilter()
)。