Duplicating an Object

Describes the clone function, used to duplicate objects.

Clone Function

Sometimes you want to create an exact copy of an object.

Simply assigning a component to a variable does not create a copy of it. Rather, it creates an additional reference to the same object. If any property of the original object changes, the new reference will also show these changes, since it is still pointing to the same object.

In order to actually create a new duplicate of the object, you can use the clone function:
// Create an instance for each
// participant in the role

for each person in activity.role.participants do
    copy = clone(this)
    copy.participant.next = person
end

Function Behavior

The clone function behaves differently depending on how the object to be cloned is implemented. To be able to respond to different conditions, the function follows the following steps:
  1. If the object you are trying to clone has a method named clone and implements the interface Cloneable, that method is used to obtain a copy.
  2. If the object implements the Serializable interface, it attempts to serialize it and deserialize it to obtain a copy of the object.
  3. Otherwise, it attempts to dynamically create a copy of it.