Synesso
Synesso

Reputation: 38958

Future yielding with flatMap

Given Futures fa, fb, fc, I can use f: Function1[(A,B,C), Future[D]], to return a Future[D] either by:

(for {
  a <- fa
  b <- fb
  c <- fc
} yield (a,b,c)).flatMap(f)

which has the unenviable property of declaring the variables a,b,c twice.

or

a.zip(b).zip(c).flatMap{ case (a, (b, c)) => f(a, b, c) }

which is terser, but the nesting of the futures into pairs of pairs is weird.

It would be great to have a form of the for-expression where the yield returns a flattened result. Is there such a thing?

Upvotes: 0

Views: 77

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

There's no reason to flatMap in the yield. It should be another line in the for-comprehension.

for {
  a <- fa
  b <- fb
  c <- fc
  d <- f(a, b, c)
} yield d

I don't think it can get more concise than that.

Upvotes: 4

Related Questions