Is there a generic way to achieve copying an existing object into another?
Assume MyObj
has an id
and name
fields. Like this:
MyObj myObj_1 = new MyObj(1, "Name 1");
MyObj myObj_2 = new MyObj(2, "Name 2");
Instead of
myObj_2.setName(myObj_1.getName()) // etc for each field
do something as following:
myObj_2.copyFrom(myObj_1)
so that they are different instances, but have equal properties.
There are several ways to copy an object, most commonly by a copy constructor or cloning. Copying is done mostly so the copy can be modified or moved, or the current value preserved. If either of these is unneeded, a reference to the original data is sufficient and more efficient, as no copying occurs.
To create a deep copy of an object in TypeScript, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. The cloneDeep method returns an object of the correct type.
The convention is to do this at construction time with a constructor that takes one parameter of its own type.
MyObj myObj_2 = new MyObj(myObj_1);
There is no Java convention to overwrite the existing properties of an object from another. This tends to go against the preference for immutable objects in Java (where properties are set at construction time unless there is a good reason not to).
Edit: regarding clone(), many engineers discourage this in modern Java because it has outdated syntax and other drawbacks. http://www.javapractices.com/topic/TopicAction.do?Id=71
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With