You use at in OCL when you need the item at a specified one-based position in a collection.
Syntax
collection->at(index : Integer) : T
collection is the collection to read from. index is an integer position, and T is the type of the returned element.
The first position is 1, not 0.
Get an item by position
- Start with the collection whose item you want to retrieve.
- Choose its one-based position: use
1for the first item,2for the second item, and so on. - Call
atwith that position.
For example, this expression retrieves the first Department instance:
Department.allInstances->at(1)
The result is one Department: the element at position 1 in the collection returned by Department.allInstances.
One-based indexing
| Expression | Position requested |
|---|---|
Department.allInstances->at(1)
|
First element |
Department.allInstances->at(2)
|
Second element |
Do not use at(0) when you mean the first element with this operator. If your expression uses zero-based indexing, use at0 instead:
Department.allInstances->at0(0)
This retrieves the first element using the zero-based at0 convention.
Choose between at and at0
| Operator | First element | Second element |
|---|---|---|
at
|
at(1)
|
at(2)
|
at0
|
at0(0)
|
at0(1)
|
Keep the indexing convention consistent within an expression. For example, if you select the first item with at(1), use at(2) to select the next item; do not switch to at0(1) unless you intend to use zero-based indexing.
