Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top