有时,我有一个Option[Future[T]]
val。我想处理它:
do.something /* Option[A] here */ map { v => // v is of type A here
doComplexCalculation(v) // it returns Future[T]
} map { v => // I want to get T here, after future becomes resolved.
// But here is Future[T] and I shoud do that:
v map { v => // v is of type T here.
}
}
从我的观点来看,坏事是增加筑巢水平。我想要更平坦的代码:)我发现的techinc之一是:
do.something /* Option[A] here */ map { v => // v is of type A here
doComplexCalculation(v) // it returns Future[T]
} getOrElse {
Future.failed(/* And I should pass Throwable here */)
} map { v => // v is of type T here
}
你能告诉我一个更好的方法吗?在我的解决方案中我不喜欢的事情:
Throwable
答案 0 :(得分:0)
为什么您的do.something
会返回选项开头?
如果你想在None的情况下失败,为什么不做。只是扔东西,或者可能返回Try
?
然后你可以做
doComplexCalculation(do.something.get).map { v: T =>
...
}
答案 1 :(得分:0)
我认为以下代码是您案例中的最佳选择
def doSomething[A](): Option[A] = ???
def complexCalculation[T](): Future[T] = ???
def someMethod() = {
val resOption = doSomething()
resOption match{
case Some(res) =>{
complexCalculation() map{ result =>
println("Future successfully resolved so print res=" + res.toString)
}
}
case None => println("doSomething returned None")
}
}