Scala: Use fold to serialize any number of Futures

Scala’s for-comprehensions are extremely useful and offer much more than just looping. For this post, I would like to focus on using for-comprehensions for manipulating Futures. More specifically, for serializing Futures.

Let’s assume that we have a function that performs some kind of logic and returns a Future:

def addOneAndPrint(num: Int): Future[Unit] = {
  Future {
    val addedOne = num + 1
    print(addedOne + " ")
  }
}
Users of such a fuction, may want to call it more than one time and additionally, to call it serially. This is easily done by using a for-comprehension like following:

for {
  _ <- addOneAndPrint(1)
  _ <- addOneAndPrint(2)
} yield (Unit)

This assures that addOneAndPrint(1) will be executed first, the result will be returned and then the addOneAndPrint(2) will be executed.

However, using the for like that, is a bit awkward if this should include many serialized calls (or unknown number of calls). For example, how could someone call the addOneAndPrint function one time for each element of a List of Integers?

val ints = List(1, 3, 5, 7, 9)

One nice solution is to use foldLeft for this List, combining a for-comprehension like following:

val dummy = Future {}
 
ints.foldLeft(dummy) {
  case (prevFuture, currentNumber) => {
    for {
      _ <- prevFuture
      _ <- addOneAndPrint(currentNumber)
    } yield (Unit)
  }
}

The output will be the result of calling the addOneAndPrint serially:

2 4 6 8 10

Thanks for reading!

scala  for  fold