创建类型集合

时间:2011-06-28 23:03:20

标签: scala

我正在尝试通过添加新集合来了解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]
}

但是我收到以下错误:

overriding method newBuilder in trait TraversableLike
   of type => scala.collection.mutable.Builder[V,NewColl[V]];
method newBuilder in trait GenericTraversableTemplate
   of type => scala.collection.mutable.Builder[V,IndexedSeq[V]] has incompatible type

任何想法?

1 个答案:

答案 0 :(得分:3)

我在类似情况下所做的是查看标准库在类似情况下的作用。查看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集合框架上构建类时,还有其他与SO相关的问题。例如5200505指向我最喜欢的文档之一The Architecture of Scala Collections。最近,Josh Suereth写了blog entry来创建自己的集合类。