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

久未见 提交于 2019-12-03 16:38:53

问题


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


回答1:


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)



回答2:


A Java-specific solution (which should work great in Scala too), is the Cloner library. It's fast, easy, deeply clones objects based on fields (using reflection), and is smart enough not to clone known immutable objects (like String, Integer, etc.). Finally, you can register custom immutable objects so it won't clone them either.

I highly recommend it.



来源:https://stackoverflow.com/questions/1267436/what-is-the-easiest-way-to-deeply-clone-copy-a-mutable-scala-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!