In Scala, does AnyRef.clone
perform a shallow or deep copy?
Default version of clone method creates the shallow copy of an object. To create the deep copy of an object, you have to override clone method. Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields.
Deep copy doesn't reflect changes made to the new/copied object in the original object. Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. Shallow copy is faster.
Whenever you try to create a copy of an object, in the deep copy all fields of the original objects are copied exactly, in addition to this, if it contains any objects as fields then copy of those is also created (using the clone() method).
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:
Long answer: Read Effective Java, 2nd Edition, Item 11: Override clone judiciously
Summary: Don't use it. There are better alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With