You can use sum in an OCL expression to total numeric values in a collection, for example the prices of a set of products.
Syntax
collection->sum
The operator is also described as sum(). Apply it to a collection whose elements support the + operation.
Parameters and return type
| Item | Description |
|---|---|
| Collection | A collection of numeric values: Integer, Real, or Decimal. |
| Return value | The total of the collection elements. The result has the same numeric type as the collection elements. |
| Collection element type | Return type |
|---|---|
| Integer | Integer |
| Real | Real |
| Decimal | Decimal |
Sum values from a collection
Use sum after navigating to a numeric collection property.
For example, this expression totals the Price values for all Product instances:
Product.allinstances.Price->sum
When the numeric value is reached through related objects, first select the objects to include and then sum their numeric property. The following expression, used with PSEvalTuples, selects billed hours after vTheStartDate and totals their Hours values:
BilledHours->select(bh|bh.WorkDate>vTheStartDate).Hours->sum
Handle nullable numeric values
If the values being summed are nullable, use value when you need a non-null numeric result. The Value operator returns the assigned underlying value, or 0 when no value is assigned.
For example, this totals product prices while ensuring that the final result has a value:
Product.allinstances.Price->sum.Value
Alternatively, convert each nullable price to a value before summing:
Product.allinstances->collect(i|i.Price.Value)->sum
Numeric sums and time sums
Use sum for numeric collections. To total DateTime, Time, or TimeSpan values as a duration, use sumTime, which returns a TimeSpan.
