14

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

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Derek Mahar
  • 27,608
  • 43
  • 124
  • 174

1 Answers1

21

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.

Walter Chang
  • 11,547
  • 2
  • 47
  • 36
  • 3
    "There are better alternatives." Would you mind referencing some? – Alex Neth Nov 10 '09 at 19:27
  • 6
    1. Copy constructor, per C++. 2. Case class with built-in "copy" method in Scala 2.8.x. 3. Use immutable objects: no need to copy, just share. – Walter Chang Nov 11 '09 at 06:34
  • So C++ -like copy constructors are actually (kind of) okay in Scala? I came to the language from C++ and before doing my first copy constructors wanted to see if I'm missing some point. Seems... it's fine (my objects have mutable state). – akauppi Oct 08 '12 at 17:08