对于Future [String]和Future [List [String]]的理解

时间:2019-07-08 16:06:38

标签: scala for-comprehension

简化代码:

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]],我也可以使用它进行理解吗?

1 个答案:

答案 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)
  }