Scala模式:对于产生未来的理解力[A] [英] Scala Pattern: For Comprehension that Yields a Future[A]
问题描述
Scala中用于处理场景的模式是什么?
What is the pattern used in Scala to deal with the scenario:
您有一堆期货(它们可以是任何东西,但是为了示例……)
You have a bunch of futures (they can be whatever, but for the sake of example...)
val aF = Future { true }
val bF = Future { Option(3) }
val cF = Future { myObject }
并且您有一些返回未来的函数
and you have some function that returns a future
def fooF: Future[SomeObject]
我想做类似的事情:
for {
a <- aF
b <- bF
c <- cF
} yield {
if (a) {
// do stuff with b & c
fooF
} else {
Future.successful(SomeObject)
}
}
我想返回值Future[SomeObject]
,但是我在yield语句中调用fooF时,我会得到一个Future[Future[SomeObject]]
I want to return a value of Future[SomeObject]
, but I call fooF inside of the yield statement, I will get a Future[Future[SomeObject]]
推荐答案
这是另一种解决方案:
def doStuffWith(a: A, b: B, c: C): Future[SomeObject] = if (a) {
// do stuff with b & c
fooF
} else Future.successful(SomeObject)
for {
a <- aF
b <- bF
c <- cF
d <- doStuffWith(a, b, c)
} yield d
正如@laughedelic答案中所讨论的,这是一个主观观点,但我认为这种方式更具可读性和可维护性(例如,始终删除该功能以对其进行单元测试).
As discussed in @laughedelic answer, this is a subjective view, but I believe this way to be more readable, and maintainable (taking out the function always to unit test it, for instance).
这篇关于Scala模式:对于产生未来的理解力[A]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!