2

While trying to clone a mutable collection, my initial approach was to use the clone() method on the mutable.Cloneable trait. However, this defers to the java.Object.clone implementation that creates a copy of the reference, not a deep copy. From testing, I can confirm that mutable.{Queue,Seq,Set} all shallow copy.

I have resorted to the crude new xxx(copy:_*) approach to create a deep copy, but my question is what is the purpose of the mutable.Cloneable trait if it is not implemented?

Woodz
  • 1,029
  • 10
  • 24

1 Answers1

5

The mutable.Cloneable trait was implemented on many collection classes. Here are a few examples:

https://github.com/scala/scala/blob/master/src/library/scala/collection/mutable/ArrayBuffer.scala#L176

https://github.com/scala/scala/blob/master/src/library/scala/collection/mutable/HashSet.scala#L82

https://github.com/scala/scala/blob/master/src/library/scala/collection/mutable/WrappedArray.scala#L78

It's just that clone is not defined to return a deep copy. The reason for this is that often you just want to copy a mutable collection so that you could modify it in some way without changing the original - the actual elements kept inside it you might want to keep the same.

If you want a deep copy, you have to either use a custom deep copying library or implement that yourself.

axel22
  • 32,045
  • 9
  • 125
  • 137