The key piece is Future.traverse
. As a first step you could write the following:
def toSet[A, B](keys: Set[A], computeValue: A => Future[B]) =
Future.traverse(keys)(computeValue)
But this returns a Future[Set[B]]
, which isn't exactly what you want. So you add in the keys and convert to a map at the end:
def toMap[A, B](keys: Set[A], computeValue: A => Future[B]): Future[Map[A, B]] =
Future.traverse(keys)(k => computeValue(k).map(k -> _)).map(_.toMap)
And you're done.