You can use isUnique in an OCL expression to verify that every element in a collection produces a different value for a specified expression.
Syntax
collection->isUnique(expr)isUnique ( expr : OclExpression ) : Boolean
The operator returns true when all elements contained in self evaluate to distinct values for expr. It returns false when two or more elements evaluate to the same value.
How it works
self is the collection on which you call the operator. The expression is evaluated once for each element in that collection, and isUnique compares the resulting values.
For example, if a person has a collection of salary values, this expression checks that no value occurs more than once:
self.salary->isUnique(s | s)If the collection contains 1000, 2000, and 3000, the result is true. If it contains 1000, 2000, and 1000, the result is false.
Use in a constraint
Use isUnique when a collection must not contain duplicate values for the property or expression you choose.
For example, the following invariant requires the values in self.salary to be unique:
context Person inv: self.salary->isUnique(s | s)The invariant evaluates to a Boolean value. It is valid only when the expression returns true.
Choosing the expression
The expression after isUnique defines what must be distinct. Select the value that represents the uniqueness rule you want to enforce.
| Expression | Checks that |
|---|---|
| s) | Every salary value in the collection is different. |
| x.someProperty) | Each element has a different value for someProperty.
|
isUnique compared with one
isUnique tests whether all evaluated values are distinct. one tests whether exactly one element satisfies a condition. Use isUnique for duplicate detection; use one when your rule requires exactly one matching element.
