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

后端 未结 2 835
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 12:11

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

2条回答
  •  爱一瞬间的悲伤
    2021-02-07 12:28

    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)
    

提交回复
热议问题