You can use let in an OCL expression to name an intermediate result and reuse it within the expression; it is intended for authors writing OCL in MDriven Designer.
Syntax
let variableName = expression in expressionThatUsesVariableName
A let expression has two parts:
- Binding:
variableName = expressionevaluates an expression and stores its result in a temporary reference. - Body: the expression after
incan use that reference.
The temporary reference exists only in the body following in. Use let when an intermediate value is needed more than once, or when giving that value a name makes the OCL easier to read.
Use a temporary result
The following expression creates a new Class2, adds it to self.Class2s, stores the returned zero-based index in x, and uses that index to access the corresponding Class3 object:
let x = self.Class2s.addReturnIndexOf0(Class2.Create) in
(
self.Class3.at0(x).Attribute1 := 'Yes'
)
In this example, x holds the result of addReturnIndexOf0. See Documentation:OCLOperators addReturnIndexOf0 for the behavior of that operator and its zero-based return value.
Chain let bindings
You can chain let bindings when a later value depends on an earlier one. Each binding introduces a temporary reference for the expression that follows it.
let xobject = SomeNewTransient.Create in
(
xobject.Key := xtuple.Part1;
xobject.SomeSum := xtuple.Part2
)
This pattern is useful inside a collection operation when each item needs a transient object. For example, a SQL pass-through result can be collected into newly created objects:
AccountPlan.SQLPassthrough('select somekey,sum(somestuff),sum(someotherstuff) from table1,2,3 where ...', String, Integer, Integer)
->collect(xtuple |
let xobject = SomeNewTransient.Create in
(
xobject.Key := xtuple.Part1;
xobject.SomeSum := xtuple.Part2
)
)
Here, xtuple is the collection variable supplied by collect, while xobject is the temporary reference introduced by let. For the SQL operation and tuple result details, see Documentation:OCLOperators sqlpassthrough.
Write readable expressions
Use descriptive temporary names that identify the value being held. For example, use xobject for a newly created object and x for an index when the expression is short. When the same intermediate result is used repeatedly, bind it once with let rather than repeating the expression.
Parentheses are useful when the body contains multiple expressions separated by semicolons, as in the examples above. They make the body of the let binding clear.
Related collection expressions
You can combine let with collection operators such as collect. If you need to construct a duplicate-free collection before iterating, use Set.
