1

I have some lambda expressions as follows:

val foo : (Int => Option[String]) = (x: Int) => Some("foo")
val bar : (Int => Option[String]) = (x: Int) => Some("bar")

Seq(foo,bar).flatMap(_ (2))

and evaluates as I expect:

res0: Seq[String] = List(foo, bar)

Now I will change the lambda expressions to the make them take an Int and return a toy Future computation:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

val foo1 : (Int => Future[Option[String]]) = (x: Int) => Future successful Some("foo")
val bar1: (Int => Future[Option[String]]) = (x: Int) => Future successful Some("bar")

I would like to get the same result back as before i.e. List("foo", "bar") but I am not sure how to achieve it. I think I need to use Monad Transformers but not entirely sure.

  • Possible duplicate of [Which Monad Transformer to use?](http://stackoverflow.com/questions/42290243/which-monad-transformer-to-use) –  Feb 18 '17 at 13:17

1 Answers1

2

You can use Future.sequence to convert the result to a Future[List] and then flatten it:

Future.sequence(Seq(foo1,bar1).map(_ (2))).map(_.flatten)

This will return a Future[List[String]], you can then handle the Future as you seem fit.

nmat
  • 7,430
  • 6
  • 30
  • 43