我有一个 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 [?]
答案 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)
number.flatMap
要求lambda返回Future[Int]
。相反,processTry
定义为: Int
。您可以将flatMap
替换为map
。num
定义为Int
,而fun
的结果为Future[Result]
。你错过了一些代码吗?val num = ...
的类型为Unit
,与功能类型不同。代码可能看起来像
def fun(number: Future[Try[Option[Int]]]): Future[Result] = {
val num: Future[Int] = number.map(x => processTry(x))
num.map{i => Result(i)}
}