Scala: How can I implement a clone method on a superclass, and use it in a subclass?

scala

Solution

Assuming you want to minimize amount of ceremony in the subclasses, here is my suggestion:

class A extends Cloneable {
  protected[this] def myCloneImpl[T] = {
    val justLikeMe = this.clone
    // copy values and such.
    // Note that the Object.clone method already made a shallow copy, but you may want
    // to deepen the copy or do other operations.
    justLikeMe.asInstanceOf[T]
  }
  def myClone = myCloneImpl[A]
}

class B extends A {
  override def myClone = myCloneImpl[B]
}

By extending java.lang.Cloneable and calling the Object.clone method, you ensure that your runtime type is the same as the object being cloned. The static type is coerced with a type-cast (asInstanceOf[T]). You will need to override the myClone method in each subclass and specify the type, but it should be a one-liner.

Problem

I might be approaching this the wrong way, but I'd like to have an object like this: ``` class MyDataStructure { def myClone = { val clone = new MyDataStructure // do stuff to make clone the same as this ... clone } } class MyDataStructureExtended(val foo: String) extends MyDataStructure ``` Then: ``` val data = MyDataStructureExtended val dataClone = data.clone println(dataClone.foo) ``` So, the problem is that dataClone is of type MyDataStructure, not MyDataStructureExtended as I'd hoped. I thought about adding a type T to the super class, that the subclass can specify (e.g. itself), but that didn't seem very promising.

Original source