为了理解 Future[String] 和 Future[List[String]]
For comprehension with Future[String] and Future[List[String]]
简化代码:
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]
}
我想要发生的是调用每对 one/many 并获得输出列表
{doSomething("1","1"),doSomething("1","2"),doSomething("1","3")}
即使一个是 Future[String]
而另一个是 Future[List[String]]
,我能否将其用于理解?
尝试
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 转换器
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)
}
简化代码:
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]
}
我想要发生的是调用每对 one/many 并获得输出列表
{doSomething("1","1"),doSomething("1","2"),doSomething("1","3")}
即使一个是 Future[String]
而另一个是 Future[List[String]]
,我能否将其用于理解?
尝试
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
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)
}