I want to create a new custom Scala collection from existing Seq collection. I have a trait named Ref which holds the data as below
trait Ref[A] {
def get: A
def getAsOption: Option[A]
def dataType: Class[A]
// other methods
}
My custom collection named Vec which is a Sequence of Ref[A] (i.e Vec[A] equivalents to Seq[Ref[A]]), the reason I want to create a custom collection like this because I want to keep the type parameter of Ref in collection to process in custom methods. My code as below
trait VecLike[A, +Repr <: Seq[Ref[A]]]
extends SeqLike[Ref[A], Repr]
with TraversableLike[Ref[A], Repr] {
// custom methods
}
trait GenVec[A]
extends VecLike[A, Seq[Ref[A]]]
with Seq[Ref[A]]
with PartialFunction[Int, Ref[A]]
abstract class AbstractVec[A](vec: Ref[A]*)
extends AbstractSeq[Ref[A]]
with GenVec[A] {...}
class Vec(vec: Ref[A]*)
extends AbstractVec[A](vec:_*)
with VecLike[A, Vec[A]]
with GenericTraversableTemplate[Ref[A], Seq]
But when I call map() function
Vec(1,2,3,4).map(intToString)
It returns a Seq[String], the expected result is Vec[String]. I also tried to create custom CanBuildFrom in companion object with SeqFactory[Seq] but it failed. :( :(
Can anybody give me some advices about this and how I implement to achieve this?
You need to implement a custom
Builderand makenewBuildermethod inVecLikereturn it. Check out this page for a very good tutorial on implementing custom collections: http://docs.scala-lang.org/overviews/core/architecture-of-scala-collections.html