Does Scala AnyRef.clone perform a shallow or deep copy?

让人想犯罪 __ 提交于 2019-11-27 03:54:27

问题


In Scala, does AnyRef.clone perform a shallow or deep copy?


回答1:


Short answer: shallow.

Not-so-short answer: Unless it's overridden, AnyRef.clone() uses the Java's Object.clone() as its implementation.

Javadoc on Object.clone():

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

Please note:

  1. AnyRef.clone(), like its counterpart in Java, has a "protected" access level, so its not callable from everywhere.
  2. You will need to implement Cloneable in order for clone() to work.

Long answer: Read Effective Java, 2nd Edition, Item 11: Override clone judiciously

Summary: Don't use it. There are better alternatives.



来源:https://stackoverflow.com/questions/1267261/does-scala-anyref-clone-perform-a-shallow-or-deep-copy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!