Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone objects in Scala?

Tags:

clone

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?

like image 695
ricardogobbo Avatar asked Jun 20 '11 21:06

ricardogobbo


2 Answers

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.

like image 102
Daniel C. Sobral Avatar answered Oct 17 '22 15:10

Daniel C. Sobral


I got a sample code that works for cloning mutable-state objects here: Implementing '.clone' in Scala

like image 41
akauppi Avatar answered Oct 17 '22 14:10

akauppi