Say you have a class Person, and create a collection class for it by extending e.g. ArrayBuffer:
class Persons extends ArrayBuffer[Person] {
// methods operation on the collection
}
Now, with ArrayBuffer, can create a collection with the apply() method on the companion object, e.g.:
ArrayBuffer(1, 2, 3)
You want to be able to do the same with Persons, e.g.:
Persons(new Person("John", 32), new Person("Bob", 43))
My first intuition here was to extend the ArrayBuffer companion object and getting the apply() method for free. But it seems that you can't extend objects. (I'm not quite sure why.)
The next idea was to create a Persons object with an apply() method that calls the apply method of ArrayBuffer:
object Persons {
def apply(ps: Person*) = ArrayBuffer(ps: _*)
}
However, this returns an ArrayBuffer[Person] and not a Persons.
After some digging in the scaladoc and source for ArrayBuffer, I came up with the following, which I thought would make the Persons object inherit apply() from GenericCompanion:
EDIT:
object Persons extends SeqFactory[ArrayBuffer] {
def fromArrayBuffer(ps: ArrayBuffer[Person]) = {
val persons = new Persons
persons appendAll ps
persons
}
def newBuilder[Person]: Builder[Person, Persons] = new ArrayBuffer[Person] mapResult fromArrayBuffer
}
However, it gives the following error message:
<console>:24: error: type mismatch;
found : (scala.collection.mutable.ArrayBuffer[Person]) => Persons
required: (scala.collection.mutable.ArrayBuffer[Person(in method newBuilder)])
=> Persons
def newBuilder[Person]: Builder[Person, Persons] = new ArrayBuffer[Perso
n] mapResult fromArrayBuffer
^
Perhaps this should disencourage me from going further, but I'm having a great time learning Scala and I'd really like to get this working. Please tell me if I'm on the wrong track. :)