简化代码:
val one: Future[String] = Future("1")
val many: Future[List[String]] = Future({"1","2","3"})
for {
a <- one
b <- many
} yield {
doSomething(a,b) // Type mismatch, expected String, actual: List[String]
}
我想发生的事情是每一对叫一对,并获得输出列表
{doSomething("1","1"),doSomething("1","2"),doSomething("1","3")}
即使其中一个是Future[String]
而另一个是Future[List[String]]
,我也可以使用它进行理解吗?
答案 0 :(得分:6)
尝试
val one: Future[String] = Future("1")
val many: Future[List[String]] = Future(List("1","2","3"))
def doSomething(a: String, b: String) = ???
for {
a <- one
b <- many
} yield {
b.map(v => doSomething(a, v))
}
或者,我们可以像这样使用scalaz ListT
变压器
import scalaz._
import ListT._
import scalaz.std.scalaFuture.futureInstance
val one: Future[String] = Future("1")
val many: Future[List[String]] = Future(List("1","2","3"))
def doSomething(a: String, b: String) = ???
for {
a <- listT(one.map(v => List(v)))
b <- listT(many)
} yield {
doSomething(a, b)
}