If I have a new collection with an additional attribute, e.g. :
class NewColl(var name: String, var values: Vector[Int])
extends IndexedSeq[Int] with IndexedSeqLike[Int, NewColl] {...}
how do I define canBuildFrom and newBuilder (cf. here) such that if:
var v1 = NewColl("foo",Vector(1,2,3))
var v2 = v1 filter(_ > 1)
var v3 = v1 map(_ + 1)
then v2.name=="foo" and v3.name=="foo"?
Try this:
Note that I’ve changed your
vars intovals here to be consistent with an immutable collection.SeqForwarderhas been mixed in to avoid implementing a list of methods that would all forward to the same method onvalues.newBuilderhas been implemented on the companion object and needs aStringparameter.Note that sometimes, collections are free to call
apply()on theCanBuildFromwithout specifying the originating collection. In that case, you either have to provide a default name, or (like here) throw an exception (permissible only if you’re not designing a library and control the use of your new collection).See also that question.