发现:scala.concurrent.Future [Option [Int]]必需:选项[?]

时间:2017-02-23 10:43:15

标签: scala

我写了这段代码

def m1(x: Int) = Future { if (x % 2 == 0) Some(x) else None }
def m2(x: Int) = Future { if (x % 2 != 0) Some(x) else None }

for {
  x <- Some(3)
  x1 <- m1(x)
  x2 <- m2(x)
} yield x1 orElse x2

我的目标是代码应该首先打开m1的未来,如果有一个,那么使用该值。否则,它应该打开m2的未来并使用该值。

但它不断收到编译错误

<console>:26: error: type mismatch;
 found   : scala.concurrent.Future[Option[Int]]
 required: Option[?]
       x1 : Option[Int] <- m1(x)

                    ^

1 个答案:

答案 0 :(得分:4)

问题在于,在理解中,从生成器获得的第一个元素 - x - 是Option,而其他元素是Future。不幸的是,Scala不支持同一种不同的发生器类型以便理解,你需要一个monad变换器来实现这一点。

简单的方法就是将选项包装在未来:

for {
  Some(x) <- Future.successful(Some(3))
  x1 <- m1(x)
  x2 <- m2(x)
} yield x1 orElse x2

我希望有所帮助。

相关问题