You use .add() in OCL to add an object to a collection or association when you want to change the underlying sequence or association.
Syntax
collection.add(object)
| Part | Meaning |
|---|---|
collection
|
The sequence or association end that receives the object. |
object
|
The object to add. Its type must be compatible with the collection element type T.
|
Add an object to an association
Use .add() when an action must establish an association between two objects.
For example, if a Department has a collection-valued association end named Employees, the following expression adds employee to that department:
self.Employees.add(employee)
After the expression runs, employee is included in self.Employees. This changes the association; it is not a temporary collection expression.
You can also add a newly created object. The following example creates a Department and adds it to the Departments association:
self.Departments.add(Department.Create)
add() versus append()
Choose the operator based on whether you need to update the source collection or calculate a new sequence.
| Operator | Use it when | Effect on the source collection |
|---|---|---|
.add(object)
|
You need to add an object to a sequence or association, such as assigning an employee to a department. | Changes the source sequence or association. |
->append(object)
|
You need a sequence that contains an extra object while leaving the source unchanged. | Does not change the source; returns a new Sequence.
|
For example, use ->append() when calculating a value without changing self.Employees:
self.Employees->append(employee)
Do not use ->append() when the purpose is to update an association.
Access an inner link created by adding
When adding an object creates an inner link object, use addReturnIndexOf0() if you need the zero-based position of the added object to access the corresponding link object.
