简体   繁体   中英

Scala: I have a Set[X] and function (X) => Future[Y] and want to output a Future[Map[X, Y]]

I have:

  • input set: Set[X] and
  • function: (X) => Future[Y]

Running the function on the set, I'd like to output a:

  • Future[Map[X, Y]]

I'm having a slow Scala brain day. Please help me come up with a transformation for the above. Thanks.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM