Search code examples
scalaclone

How to clone objects in Scala?


Recently had some problems to copy a complex object. Its internal organization is composed of several nested objects. I noticed that the clone() is not available.

What is the best solution to solve the problem?


Solution

  • If that complex object is mutable or contain mutable parts, then the solution is the same as in Java. Check Java questions & posts about it and do that.

    If everything is immutable, then you don't need and shouldn't clone anything. At best, you should make a shallow copy of the object, changing only the fields that need changing, and, at worst, you use something like lenses or zippers to copy some deep object and propagate the change upwards. See questions on Scala about lenses and zippers for that.