【问题标题】:How to make a function working with different collection type in Scala 2.13?如何使函数在 Scala 2.13 中使用不同的集合类型?
【发布时间】:2021-10-14 05:09:12
【问题描述】:

以下函数或多或少地接受任何集合并将其过滤返回:

def filterEven[Repr](o: collection.IterableLike[Int, Repr]): Repr = {
  o.filter { o =>
    (o % 2) == 0
  }
}

filterEven(List(1, 2, 3))

filterEven(Set(1, 2, 3))

如何使用 Scala 2.13 实现相同的目标? IterableLike 不再存在。我应该以某种方式使用更高种类的类型吗?

【问题讨论】:

标签: scala collections scala-2.13


【解决方案1】:

似乎可以使用更高种类的类型和IterableOps 来实现这一点:

def filterEven[CC[Int] <: IterableOps[Int, CC, CC[Int]]](o: CC[Int]): CC[Int] = {
  o.filter { o =>
    (o % 2) == 0
  }
}

我发现这比之前基于 Repr 的解决方案更合乎逻辑。

灵感来自Adding custom collection operations in scala 2.13 to arbitrary collections of specific types

【讨论】:

  • 这不会让你使用像BitSet 这样的类型,不确定这是否适合你的用例。
  • 我的 Scala 2.12 也仅适用于 Iterables,因此我可以使用(我需要 List 和 Set)。您的IsIterable 解决方案看起来也不错。感觉有点奇怪BitSet有IsIterable,但是IterableOps不接受。
  • 是的,整个 stdlib 集合层次结构很奇怪,几年前我放弃了尝试理解它;我只是在有意义的时候使用 cats 类型类和几个IsIterableOnce 来接受任何东西。
  • 您仍然可以将IterableOps 用于具有两个类型参数的 BitSet 之类的东西:def filterEven[CC[_], C](col: IterableOps[Int, CC, C]): C。它会将 Array 转换为 ArraySeq,因为 Array 没有扩展 IterableOps
猜你喜欢
  • 1970-01-01
  • 2021-06-09
  • 2021-07-25
  • 2019-08-08
  • 2021-04-19
  • 2015-01-27
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
相关资源
最近更新 更多