문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top