问题
I've got troubles with cloning in Scala. Is this possible to clone an object of an arbitrary type T? Something like this:
import collection.immutable.Stack
object Tester extends App {
trait Grand[T <: Cloneable] {
val stack = Stack[T]()
val h: T
def snapshot() {
stack push h.clone().asInstanceOf[T]
}
}
}
however it throws:
scala: method clone in class Object cannot be accessed in T
Access to protected method clone not permitted because
prefix type T does not conform to
trait Grand in object Tester where the access take place
What goes wrong there?
回答1:
I was advised on this question. In such a situation the best approach is to use structural typing:
trait Grand[T <: {def cloneObject: T}]
so that the user code might be the following:
case class Person(name: String) {
def cloneObject = copy()
}
object Roll extends App with Grand[Person] {
...
}
回答2:
clone() is from java.lang.Object not from java.lang.Cloneable. Cloneable is just a tagging-interface.
What you are trying probably does not work because implementing Cloneable does not force the implementor to override the protected Object.clone() with a public one.
see http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone() and http://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html
ln conclusion: No it is not possible to clone an object of an arbitrary type T1. You could however clone any object of type T2 where T2 is bound by a type with a public override of clone(). Your example fails because Object.clone() is protected, i.e. can only be called from within a subclass.
来源:https://stackoverflow.com/questions/15860647/scala-method-clone-in-class-object-cannot-be-accessed-in-t-access-to-protected-m