You use the first operator in OCL to get the first object from a collection, for example when you need one Customer from a filtered set.
Syntax
collection->first
If the operand is not already a collection, OCL converts it to a list before it evaluates first.
Return value
The operator returns the first element in the collection. If the collection has no element, the result is null.
For example, you can test whether any Car exists before using the result, as shown in if.
Examples
Get the first object of a class
Customer.allInstances->first
This returns the first Customer object in the system, or null if there are no Customer objects.
self.Orders->first
When self is a Customer, this returns the first Order linked to that Customer.
Filter, then get one matching object
Customer.allInstances->select(a|a.Age>50)->first
This first selects Customer objects whose Age is greater than 50, then returns the first Customer in that result. If no Customer is older than 50, the expression returns null.
Choose the right operator
| Need | Operator | Example |
|---|---|---|
| Get the first element | first
|
self.Orders->first
|
| Get an element at a specified zero-based position | at0 | self.Orders->at0(0)
|
Use first when you want the first available element. Use at0 when the expression must name a particular zero-based index.
