What is the easiest way to deeply clone (copy) a mutable Scala object?
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
So similar to the above cloning approaches, we can achieve deep cloning functionality using object serialization and deserialization as well, and with this approach, we do not have worry about or write code for deep cloning — we get it by default.
If you simply want to deep copy the object to another object, all you will need to do is JSON. stringify the object and parse it using JSON. parse afterward. This will essentially perform deep copying of the object.
Since you want the easiest way to deep copy a Scala object and not the fastest, you can always serialize the object, provided that it's serializable, and then deserialize it back. The following code only runs when compiled, not in REPL.
def deepCopy[A](a: A)(implicit m: reflect.Manifest[A]): A =
util.Marshal.load[A](util.Marshal.dump(a))
val o1 = new Something(...) // "Something" has to be serializable
val o2 = deepCopy(o1)
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