未来[尝试[Option [Int]]]发现错误:models.TenantGlobalBranding [error] required:scala.concurrent.Future [?]

时间:2017-04-24 06:42:52

标签: scala playframework future

我有一个 Int:Future [Try [Option [Int]]] ,我需要这个Int值。我有这样的代码:

def fun(number: Future[Try[Option[Int]]]): Future[Result] = {
  val num: Int = number.flatMap(x => processTry(x))
}

def processTry(x: Try[Option[Int]]): Int = processOption(x.getOrElse(Some(101)))
def processOption(x: Option[Int]): Int = x.getOrElse(101)

我收到此错误必需:scala.concurrent.Future [?]

2 个答案:

答案 0 :(得分:1)

您可以利用模式匹配来非常干净地处理答案和错误案例:

val result: Future[Try[Option[Int]]]
result.onComplete {
  case Success(Success(Some(i))) => // you get your i: Int
  case Success(Success(None)) => // you get None
  case _ => // Either the `Future` or the `Try` failed, you could also process both cases separately
}

答案 1 :(得分:0)

  1. 您的number.flatMap要求lambda返回Future[Int]。相反,processTry定义为: Int。您可以将flatMap替换为map
  2. 您已将num定义为Int,而fun的结果为Future[Result]。你错过了一些代码吗?
  3. val num = ...的类型为Unit,与功能类型不同。
  4. 代码可能看起来像

    def fun(number: Future[Try[Option[Int]]]): Future[Result] = {
      val num: Future[Int] = number.map(x => processTry(x))
      num.map{i => Result(i)}
    }