Combining Scala Futures and collections in for comprehensions

The Future companion object has a traverse method that does exactly what you want:

val allTheSquares: Future[List[Int]] =
  Future.traverse(numberList)(squareInTheFuture)

This will asynchronously start all the computations and return a future that will be completed once all of those futures are completed.


flatMap requires that the type constructors of numberList and squareInTheFuture(number) are the same (modulo whatever implicit conversions the collection library does). That isn't the case here. Instead, this is a traversal:

val allSquaresInTheFuture: Future[List[Int]] =
    Future.traverse(numberList)(squareInTheFuture)

@Lee is correct. As an addition, if you are trying to do parallel computation:

  val numberList = List(1, 2, 3)
  val allTheSquares = numberList.par.map(x => x * x)(breakOut)

If you really want Future:

val allTheSquares: Future[List[Int]] = Future.traverse(numberList)(squareInTheFuture)

Tags:

Scala