0

I want to avoid creating intermediate Seq using zipped in a for-comprehension like:

def flat(as: Seq[Int], bs: Seq[Int], cs: Seq[Int], ds: Seq[Int]): Seq[Int] = for{
  (a,b) <- (as, bs).zipped
  (c,d) <- (cs, ds).zipped
} yield a + b + c + d

But zipped (Tuple2Zipped) flatMap returns Traversable by default, not Seq. If I write the same code using explicit map and flatMap I could give it the suitable canBuildFrom to output a Seq.

So, how the for-comprehension choose the canBuildFrom for the flatMap and is it possible to tell it which one to use?

Juh_
  • 14,628
  • 8
  • 59
  • 92
  • It's probably a duplicate with a [super-detailed answer here](https://stackoverflow.com/questions/1715681/scala-2-8-breakout?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa), but tl;dr, sorry. Also [this here](https://stackoverflow.com/questions/4213992/can-i-use-for-comprehenion-yield-to-create-a-map-in-scala?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) seems similar, but for `Map`s. – Andrey Tyukin Jun 05 '18 at 14:20

1 Answers1

1

Just append breakOut immediately after the for-comprehension enclosed in parentheses:

def flat(as: Seq[Int], bs: Seq[Int], cs: Seq[Int], ds: Seq[Int])
: Seq[Int] = (for{
  (a,b) <- (as, bs).zipped
  (c,d) <- (cs, ds).zipped
} yield a + b + c + d)(collection.breakOut)

This works with any other CanBuildFrom that you want.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93