You can use size() in OCL to count the elements in a collection; use it when you need an integer such as the number of related objects on an association.
Syntax and result
collection->size()
object.size()The result is an Integer.
When the operand is not already a collection, MDriven treats it as a collection containing that one value before counting. Therefore, a non-collection value has a size of 1.
| Operand | Expression | Result |
|---|---|---|
| A collection of orders | customer.Orders->size()
|
The number of orders related to customer
|
| One object or value | anObject.size()
|
1, because the value is treated as a one-item collection
|
For example, count the orders belonging to the first Customer returned by allinstances:
Customer.allinstances->first.Orders->size()This expression is evaluated from left to right:
Customer.allinstancesreturns the Customer objects in the system.->firstselects the first Customer from that collection..Ordersfollows the Orders association for that Customer.->size()returns the number of Order objects in that association collection.
If that Customer has three related orders, the expression returns 3.
Use size() for counts, not emptiness
Use size() when you need the count itself, for example in a comparison:
customer.Orders->size() > 0When you only need to determine whether a collection contains any elements, use isEmpty() or its related non-empty check instead. Do not use collection-emptiness operators on a value type: MDriven converts a value to a one-item collection, so it is not empty.
Strings
For string character counts, use length, which is specific to strings and returns the number of characters.
