You use ->exists in OCL to test whether at least one object in a collection meets a Boolean condition.
Purpose
->exists evaluates a condition for the elements of a collection. It returns true when one or more elements satisfy the condition; it returns false when no element satisfies it.
For example, you can determine whether any Customer has the name 'John'.
Customer.allInstances()->exists(o | o.name = 'John')
This expression returns true if at least one Customer has the name John.
Syntax
collection->exists(variable | condition)
| Part | Meaning |
|---|---|
collection
|
The list, set, or other enumerable collection to inspect. |
variable
|
A local placeholder for the current element in the collection. |
condition
|
A Boolean expression evaluated for each element. The expression must be true for an element to count as a match. |
Examples
Test all instances of a class
Use allInstances() when the collection is all objects of a class.
Customer.allInstances()->exists(o | o.name = 'John')
The variable o represents one Customer at a time. A Customer named John makes the whole expression true.
You can also test a collection reached through a role. The following expression tests whether a Customer has an Order whose status is 'Open'.
self.Orders->exists(o | o.status = 'Open')
Here, self.Orders is the collection being inspected, and o represents one Order in that collection.
| Operator | Use it when you need to know | Example |
|---|---|---|
| condition) | Whether at least one element meets a condition. | o.status = 'Open') |
| condition) | Whether every element meets a condition. | o.status = 'Open') |
->existing
|
Whether a collection contains at least one object that still exists and has not been deleted. It does not evaluate a condition. | self.Orders->existing
|
Use ->exists when the result depends on a condition such as an attribute value. Use ->existing when you only need to verify that at least one valid, non-deleted object remains in the collection.
