OCLOperators asBag
Created by Alexandra on 2017-08-13 · Last edited by Colline.ssali on 2025-12-23.
Returns a Bag containing all elements of self.
The asBag() operator converts a value or collection into a Bag, which is an unordered collection that allows duplicate elements. Unlike a Set, a Bag does not enforce uniqueness, meaning the same element can appear multiple times. This operator is useful when you want to preserve duplicate entries while still working with collection-based OCL operations. When applied to a single object, asBag() wraps it into a Bag containing that one element; when applied to an existing collection, it keeps all duplicates intact.
| Expression | Result |
|---|---|
| Sequence{'3', 1, 2.0, '3'}->asBag() | Bag{2.0, '3', 1, '3'} |
| Bag{1, 2.0, '3'}->asBag() | Bag{2.0, 1, '3'} |
| OrderedSet{1, 2.0, '3'}->asBag() | Bag{2.0, 1, '3'} |
| OrderedSet{1, 1, 2.0, '3'}->asBag() | Bag{'3', 1, 2.0} |
| Set{1, 2.0, '3'}->asBag() | Bag{2.0, 1, '3'} |
| Set{1, 1, 2.0, '3'}->asBag() | Bag{2.0, '3', 1} |
Example:
Department.allInstances.asBag()This returns a Bag of Department objects, including duplicates if they exist.
