在Scala中实现'.clone'

aka*_*ppi 4 scala

我想.clone在Scala中弄清楚如何使用自己的对象.

这是一个模拟,所以可变状态是必须的,从而产生了克隆的全部需求.在向前移动模拟时间之前,我将克隆整个状态结构.

这是我目前的尝试:

abstract trait Cloneable[A] {
  // Seems we cannot declare the prototype of a copy constructor
  //protected def this(o: A)    // to be defined by the class itself

  def myClone= new A(this)
}

class S(var x: String) extends Cloneable[S] {
  def this(o:S)= this(o.x)    // for 'Cloneable'
  def toString= x
}

object TestX {
  val s1= new S("say, aaa")
  println( s1.myClone )
}
Run Code Online (Sandbox Code Playgroud)

一个.为什么上面没有编译.得到:

error: class type required but A found
  def myClone= new A(this)
                   ^

湾 有没有办法在特征中声明复制构造函数(def this(o:A)),以便显示使用特征的类需要提供一个.

C.说abstract trait什么有什么好处?

最后,对于所有这些,有没有更好的标准解决方案?

我研究过Java克隆.似乎不适合这个.Scala copy也不是 - 它只适用于案例类,它们不应该具有可变状态.

感谢您的帮助和任何意见.

Nic*_*ick 9

特征不能定义构造函数(我认为abstract对特征没有任何影响).

是否有任何理由需要使用复制构造函数而不仅仅是实现克隆方法?有可能不必在类上声明[A]类型,但我至少声明了一个self类型,因此编译器将确保类型与类匹配.

trait DeepCloneable[A] { self: A =>
    def deepClone: A
}

class Egg(size: Int) extends DeepCloneable[Egg] {
    def deepClone = new Egg(size)
}

object Main extends App {
    val e = new Egg(3)
    println(e)
    println(e.deepClone)
}
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/CS9HTW

  • 没有必要,但是停止你做类似'class Egg扩展DeepCloneable [Potato]`. (2认同)