是否可以将canBuildFrom传递给for-comprehension?

时间:2018-06-05 14:01:07

标签: scala for-comprehension

我想避免使用zip括号来创建中间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默认返回Traversable,而不是Seq。如果我使用显式map和flatMap编写相同的代码,我可以给它合适的canBuildFrom来输出Seq。

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

1 个答案:

答案 0 :(得分:1)

在括号内的breakOut - 理解之后立即附加for

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