DidUMeanRecursion
DidUMeanRecursion

Reputation: 57

For comprehension with Future[String] and Future[List[String]]

Simplified code:

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]
}

What I want to happen is to call for each couple of one/many and get a list of the outputs

 {doSomething("1","1"),doSomething("1","2"),doSomething("1","3")}

Can I get this to work with for comprehensions even when one is a Future[String] and the other a Future[List[String]]?

Upvotes: 1

Views: 100

Answers (1)

Mario Galic
Mario Galic

Reputation: 48400

Try

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

Alternatively we could use scalaz ListT transformer like so

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

Upvotes: 6

Related Questions