You use asSet() in OCL expressions when you need a duplicate-free, unordered Set from a value or another collection.
Signature
asSet() : Set(T)
asSet() returns a Set containing the elements of self. A Set is an unordered collection: it contains each element at most once.
Convert a collection to a Set
Use asSet() when an expression returns a collection that may contain repeated values and the next part of the expression requires unique elements.
For example, this Sequence contains 'EmailAddress' twice:
Sequence{'String', 'EmailAddress', 'EmailAddress'}->asSet()Result:
Set{'String', 'EmailAddress'}The duplicate 'EmailAddress' is removed. Do not rely on the displayed order of the result: a Set is unordered.
Convert a single value to a Set
When self is one value, asSet() creates a Set with that value as its single element.
'EmailAddress'->asSet()Result:
Set{'EmailAddress'}This is useful when you must supply a Set to a later collection expression but currently have one value.
Use the result in a collection expression
For example, convert repeated integers to a Set before applying collect:
Sequence{14, 22, 14}->asSet()->collect(i | DoSomthingWithAnInt(i))DoSomthingWithAnInt(i) is evaluated once for 14 and once for 22, because the Set has no duplicates.
When to use asSet
| Situation | Use asSet()?
|
Reason |
|---|---|---|
| You need unique elements from an existing collection | Yes | It returns a Set and removes duplicates. |
| You have one value but need a Set | Yes | It wraps the value in a one-element Set. |
| You need to preserve collection order | No | A Set is unordered; use Sequence when order matters. |
| You are creating a fixed Set directly | Usually no | Create it with Set{...}; see Set.
|
