是否可以将 canBuildFrom 传递给理解?

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

我想避免使用 zipped in for-comprehension 创建中间 Seq,例如:

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

但压缩 (Tuple2Zipped) flatMap returns 默认情况下可遍历,而不是 Seq。如果我使用显式 map 和 flatMap 编写相同的代码,我可以给它合适的 canBuildFrom 来输出 Seq.

那么,for-comprehension 如何为 flatMap 选择 canBuildFrom 并且可以告诉它使用哪一个?

只需在括号中的 for 后立即附加 breakOut

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)

这适用于您想要的任何其他 CanBuildFrom