【问题标题】:is it possible to pass the canBuildFrom to a for-comprehension?是否可以将 canBuildFrom 传递给理解?
【发布时间】:2018-06-05 14:01:06
【问题描述】:

我想避免使用 zipped 来创建中间序列,例如:

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

但是 zipped (Tuple2Zipped) flatMap 默认返回 Traversable,而不是 Seq。如果我使用显式 map 和 flatMap 编写相同的代码,我可以给它合适的 canBuildFrom 来输出 Seq。

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

【问题讨论】:

标签: scala for-comprehension


【解决方案1】:

只需在括号中的for-comprehension 之后立即附加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

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多