Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to deeply clone (copy) a mutable Scala object?

Tags:

clone

scala

What is the easiest way to deeply clone (copy) a mutable Scala object?

like image 597
Derek Mahar Avatar asked Aug 12 '09 17:08

Derek Mahar


People also ask

Does clone () make a deep copy?

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.

Can we achieve deep cloning of an object by serialization?

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.

How do you deep copy an object in es6?

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.


1 Answers

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)
like image 69
Walter Chang Avatar answered Oct 06 '22 08:10

Walter Chang