我想知道如何在Scala中使用.clone
我自己的对象。在Scala中实现'.clone'
这是一个模拟所以可变状态是必须的,并且由此产生了对整个克隆的需要。在将模拟时间提前之前,我将克隆整个状态结构。
这是我目前的尝试:
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)
}
一个。为什么上面没有编译。提供:
error: class type required but A found def myClone= new A(this) ^
b。是否有办法在特征中声明拷贝构造函数(def this(o:A)
),以便使用特征的类将被显示为需要提供一个特征。
c。说abstract trait
有什么好处吗?
最后,有没有更好的方法,所有这一切的标准解决方案?
我已经研究过Java克隆。似乎不是为了这个。此外Scala copy
不是 - 它只适用于case类,它们不应该有可变状态。
感谢您的帮助和任何意见。
如果你克隆状态_every time step_那么为什么“可变状态是必须的”?只有当你不需要每次都创建一个克隆时,可变性才是有效的。 –