scalafinaglefinatra

How to convert a Future[Seq[A]] to a Future that contains Seq[A]?


I'm working on a Finatra app where I have a Future[Seq[A]] (from Finagle call). However, I need to convert that to a new object that contains Seq[A], for example

case class Container[A](s: Seq[A])

That would result in Future[Container].

While I can perform map on Future[Seq[A]], it's unclear how to arrive at Future[Container[Seq[A]].


Solution

  • .map over the Future with Container.apply:

    scala> case class Container[A](s: Seq[A])
    defined class Container
    
    scala> val f = Future.successful(List(1, 2, 3))
    f: scala.concurrent.Future[List[Int]] = scala.concurrent.impl.Promise$KeptPromise@3f363cf5
    
    scala> f.map(Container.apply)
    res2: scala.concurrent.Future[Container[Int]] = scala.concurrent.impl.Promise$DefaultPromise@3d829787
    
    scala> res2.value
    res3: Option[scala.util.Try[Container[Int]]] = Some(Success(Container(List(1, 2, 3))))
    

    f.map(Container.apply) is short for f.map(Container.apply(_)), which in turn is short for f.map(v => Container.apply(v)).

    Note that you could also write it f.map(Container(_)), whichever you prefer.