【问题标题】:Creating typed collection创建类型化集合
【发布时间】:2011-09-24 17:44:47
【问题描述】:

我试图通过添加一个新集合来理解 Scala 集合,如下所示:

class NewColl[V](values:Vector[V],someOtherParams)
extends IndexedSeq[V] with IndexedSeqLike[V, NewColl[V]] {

  def fromSeq[V](seq: Seq[V]): NewColl[V] = ...

  override def newBuilder[V]: Builder[V, NewColl[V]] =
    new ArrayBuffer[V] mapResult fromSeq[V]
}

但我收到以下错误:

在 trait TraversableLike 中重写方法 newBuilder 类型 => scala.collection.mutable.Builder[V,NewColl[V]]; 特征 GenericTraversableTemplate 中的方法 newBuilder 类型 => scala.collection.mutable.Builder[V,IndexedSeq[V]] 的类型不兼容

有什么想法吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    我在类似情况下所做的就是看看标准库在类似情况下做了什么。查看IndexedSeq 的具体子类,它们似乎混入了GenericTraversableTemplate。考虑到这一点,我会重新编写代码以使用它:

    import collection.mutable._
    import collection.generic.GenericTraversableTemplate
    import collection.generic.GenericCompanion
    
    class NewColl[V](values:Vector[V]) extends IndexedSeq[V] with 
        GenericTraversableTemplate[V, NewColl] {
    
      def fromSeq[V](seq: Seq[V]): NewColl[V] = new NewColl(Vector(seq: _*))
    
      override def companion: GenericCompanion[NewColl] = new GenericCompanion[NewColl]() {
        def newBuilder[A]: Builder[A, NewColl[A]] = new Builder[A, NewColl[A]] {
          val elems = new ArrayBuffer[A]()
          def +=(a:A) = { elems += a; this } 
          def clear() { elems.clear }
          def result(): NewColl[A] = fromSeq(elems)
        }
      }
    
    }
    

    (为了清楚起见,删除了 someOtherParams

    请注意,还有其他关于在 scala 2.8 集合框架上构建类的问题。例如5200505 指向我最喜欢的文档之一The Architecture of Scala Collections。同样在最近,Josh Suereth 写了一个 blog entry 来创建你自己的集合类。

    【讨论】:

    • map 的结果仍然是 IndexedSeq 而不是 NewColl!
    • @teucer,你需要提供一个CanBuildFrom,见scala-lang.org/docu/files/collections-api/…。我建议略读/阅读Scala 集合的架构,然后尝试实现您的集合。无缘无故地做相反的事情更具挑战性。
    猜你喜欢
    • 2015-01-09
    • 2018-02-16
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多