Search code examples
listscalaseq

Transform from List[Future[...] to List[...] in Scala


Is there a method (or simple way) in scala that helps to transform List[Future[...]] to List[...]?

If such a method is in the Seq, then it is also suitable. I spent a lot of time looking, but I couldn't find anything. Thanks


Solution

  • sequence can turn List[Future[A]] to Future[List[A]] and then you could await the future

    val fxs: Future[List[Int]] = Future.sequence(List(Future(1), Future(2)))
    val xs: List[Int] = Await.result(fxs, Duration.Inf)
    // work with xs
    

    however usually it is preferable to map over the future instead of awaiting like so

    fxs.map { xs: List[Int] =>
      // work with xs
    }