Search code examples
scalafunctional-programmingfor-comprehension

Composing Futures and Options


I have four types A,B, C and D, an initial value x of the type Future[Option[A]] and three functions: f1: A => Option[B] , f2: B => Future[Option[C]] and f3: C => D.

How can I write a for comprehension starting with x that results in a value of the type Future[Option[D]] that would be the "composition" of the three functions?


Solution

  • You can use monad transformers (from Scalaz) for this:

    import scalaz.OptionT
    import scalaz.std.option._
    import scalaz.syntax.monad._
    val result: Future[Option[D]] = (for {
      a <- OptionT(x)
      b <- OptionT(f1(a).point[Future])
      c <- OptionT(f2(b))
    } yield f3(c)).run
    

    You'll need a monad instance for Future; there's one in scalaz-contrib.