You can use addReturnIndexOf0 in OCL when you need to add an object to a collection and immediately use the zero-based position at which it was added; it is particularly useful when adding through an innerlink association.
What addReturnIndexOf0 does
addReturnIndexOf0 adds an object to a collection, like a normal add operation, and returns the zero-based index of the added object.
A zero-based index starts at 0. For example, if the added object becomes the first object in the collection, the operation returns 0. You can use that returned value with at0 to access the object at the same position in another collection.
Use it with an innerlink
An innerlink is an association where adding an object through one collection results in creation of a link object. In the following example, adding a new Class2 object to Class1.Class2s creates a related Class3 link object.
Use addReturnIndexOf0 to retain the position of the added Class2, then use that position to retrieve the corresponding Class3 object and set its attribute.
Store the index in a variable
Use a let expression when you want the index to be named and the expression to be easier to read:
let x=self.Class2s.addReturnIndexOf0(Class2.Create) in
(
self.Class3.at0(x).Attribute1:='Yes'
)
In this example:
Class2.Createcreates theClass2object that is added.self.Class2s.addReturnIndexOf0(...)adds that object and returns its zero-based position, stored inx.self.Class3.at0(x)retrieves theClass3link object at the same position.Attribute1:='Yes'updates the attribute on that link object.
Use the returned index inline
When the index is only needed once, use the operation directly inside at0:
self.Class3.at0(self.Class2s.addReturnIndexOf0(Class2.Create)).Attribute1:='Yes2'
This expression performs the same work as the previous example. The let version is usually easier to maintain when you need to use the returned index more than once.
Choose the expression form
| Situation | Recommended form |
|---|---|
| You use the returned index once. | Use the inline expression. |
| You use the returned index more than once, or want to make the logic clearer. | Store it with let.
|
| You must update the innerlink object created by adding through an association. | Use the returned index with at0 to access the corresponding link object.
|
Important considerations
- The returned value is an index, not the added object itself.
- The index is zero-based, so the first position is
0. - The innerlink example relies on the
Class2sandClass3collections having corresponding positions after the add. Use the returned index with the collection that contains the created link objects. - Use the OCL general operators documentation to explore available OCL operators in the OCL editor.
