gpt4 book ai didi

scala - Future[Option[Future[Option[Boolean]]] 简化 future 和期权?

转载 作者:行者123 更新时间:2023-12-04 18:10:05 31 4
gpt4 key购买 nike

我一直试图简化我在 Scala 中做 future 的方式。我有一次收到了 Future[Option[Future[Option[Boolean]]但我在下面进一步简化了它。有没有更好的方法来简化这个?

传递“失败”的 future 似乎不是做到这一点的最佳方式。即在顺序世界中,我只是简单地返回“失败!!”任何时候它失败了,而不是继续到最后。还有其他方法吗?

val doSimpleWork = Future {
//Do any arbitrary work (can be a different function)
true //or false
}

val doComplexWork = Future {
//Do any arbitrary work (can be a different function)
Some("result") //or false
}

val failed = Future {
//Do no work at all!!! Just return
false
}

val fut1 = doSimpleWork
val fut2 = doSimpleWork

val fut3 = (fut1 zip fut2).map({
case (true, true) => true
case _ => false
})

val fut4 = fut3.flatMap({
case true =>
doComplexWork.flatMap({
case Some("result") =>
doSimpleWork
case None =>
failed
})
case false =>
failed
})

fut4.map({
case true =>
"SUCCESS!!!"
case _ =>
"FAIL!!"
})

最佳答案

请注意,在您的示例中,因为您急切地实例化 Futuresval ,所有这些都会在您声明它们后立即开始执行( val x = Future {...} )。相反,使用方法将使 Futures 仅在执行链请求时才执行。

避免进一步计算的一种方法是抛出异常,然后用 onFailure 处理它。 :

def one = future { println("one") ; Some(1) }
def two = future { println("two") ; throw new Exception("no!"); 2 }
def three = future { println("three") ; 3 }

val f = one flatMap {
result1 => two flatMap {
result2 => three
}
}

f onFailure {
case e: Exception =>
println("failed somewhere in the chain")
}

你可以在这里看到“三个”不应该被打印出来,因为我们在 two 上失败了。 .情况是这样的:
one 
two
failed somewhere in the chain

关于scala - Future[Option[Future[Option[Boolean]]] 简化 future 和期权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16291506/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com