Search code examples
scalafuture

Scala: Convert a vector of tuples containing a future to a future of a vector of tuples


I'm looking for a way to convert a Vector[(Future[TypeA], TypeB)] to a Future[Vector[(TypeA, TypeB)]].

I'm aware of the conversion of a collection of futures to a future of a collection using Future.sequence(...) but cannot find out a way to manage the step from the tuple with a future to a future of tuple.

So I'm looking for something that implements the desired functionality of the dummy extractFutureFromTuple in the following.

val vectorOfTuples: Vector[(Future[TypeA], TypeB)] = ...
val vectorOfFutures: Vector[Future[(TypeA, TypeB)]] = vectorOfTuples.map(_.extractFutureFromTuple)
val futureVector: Future[Vector[(TypeA, TypeB)]] = Future.sequence(vectorOfFutures)

Solution

  • Note that you can do this with a single call to Future.traverse:

    val input: Vector[(Future[Int], Long)] = ???
    val output: Future[Vector[(Int, Long)]] = Future.traverse(input) {
      case (f, v) => f.map(_ -> v)
    }