Creating typed collection
II am trying to understand Scala collections by adding a new collection as follows:
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] map开发者_开发百科Result fromSeq[V]
}
but I get the following error:
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
Any Idea?
What I do in similar cases is to look at what the standard library does in similar cases. Looking at concrete subclasses of IndexedSeq
they seem to mix in GenericTraversableTemplate
. With that in mind, reworking your code to use it I get:
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)
}
}
}
(with someOtherParams removed for clarity)
Note that there are other questions on SO related to building classes on the scala 2.8 collection framework. For instance 5200505 which points to one of my favorite document The Architecture of Scala Collections. Also recently, Josh Suereth wrote a blog entry on creating your own collection class.
精彩评论