Search code examples
scalafor-comprehension

is it possible to pass the canBuildFrom to a for-comprehension?


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?


Solution

  • 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.