🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators asBag
This page was created by Alexandra on 2017-08-13. Last edited by Wikiadmin on 2026-07-29.

You can use asBag() in an OCL expression when you need an unordered collection that retains duplicate elements.

What asBag() returns

asBag() converts its receiver (the value or collection before ->asBag()) to a Bag. A Bag is an unordered collection in which the same value can occur more than once.

When you apply the operator to a single object, the result is a Bag containing that object. When you apply it to a collection, the result is a Bag and any duplicates already present in the collection remain present.

Use asBag() when duplicates matter

Use asBag() when a later collection expression must be able to retain multiple occurrences of the same value. Do not use it to remove duplicates.

For example, this expression turns the current object into a one-element Bag:

self->asBag()

If self is a Department, the result is a Bag containing that Department.

This expression converts a collection reached through the Departments role into a Bag:

self.Departments->asBag()

The result contains the Department objects from self.Departments. If the input collection contains the same Department more than once, the Bag retains those occurrences.

Bag compared with Set

Collection type Element order Duplicate elements When to use it
Bag Unordered Retained You need collection operations to keep repeated values.
Set Unordered Removed You need each value only once.

For example, Set{'String', 'EmailAddress'} is a Set, so it cannot contain the same string twice. Converting that Set with ->asBag() changes the collection type to Bag, but it cannot recreate duplicates that the Set has already removed.

Important behavior

  • A Bag is unordered. Do not use asBag() when your expression depends on element order.
  • asBag() preserves duplicates that exist in the input; it does not add duplicates.
  • Converting a Set to a Bag does not restore values previously removed by Set uniqueness.
  • Use collection operators such as intersection with attention to their declared collection types and return values.

Finding operators

To inspect the operators available for a type in MDriven Designer, open the OCL Editor and type the class or expression. See Documentation:OCL General Operators for this workflow.

See also