Scala 斯卡拉。展开选项的最佳方式[未来[T]]
有时,我有一个Scala 斯卡拉。展开选项的最佳方式[未来[T]],scala,functional-programming,Scala,Functional Programming,有时,我有一个选项[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
选项[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
}
你能告诉我一个更好的方法吗?解决方案中我不喜欢的东西:
为什么您的
会这样做。something
首先返回一个选项?
如果你想在“无”的情况下失败,为什么不这样做呢?
那你就可以这么做了
doComplexCalculation(do.something.get).map { v: T =>
...
}
我认为以下代码是您的最佳选择
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")
}
}
这是不可接受的,因为
do.something
可能是长链代码,例如:something.map{}map{}map{}map(doComplexCalculation),如果是这种情况,请不要使用选项。只要Future[T]
就足够了。似乎如果选项
为无
,您将返回失败的未来
。因此,这个额外的起始级别(选项
的未来
)是不必要的。我不能改变做什么。但是谢谢你,我会在我的新代码中考虑这个问题。谢谢你的参与,但这是不可接受的,因为它有同样的缺点:增加筑巢水平。依我看,我的第二个例子更好。