To initialize local variables, you can use either literal expressions, variable reference expressions, or functional expressions. These expressions can reference any other local variables within their scope or any input or global variables.
As a best practice, declare local variables within do scopes (see Flow Control in DataWeave). The alternative method of declaring a scope with the using keyword is no longer recommended and available only to provide compatibility.
You can only reference a local variable by name from within the scope of the expression that initializes it. The declaration can be prepended to any literal expression. The literal delimits the scope of the variable, so you cannot reference any variable outside of its scope.
The examples that follow show initialization of local variables.
Example: Scoped to a Simple Value
The following example sets the local variable myVar in a do scope. It calls do from the body of the DataWeave script:
%dw 2.0
output application/json
---
do {
var myVar = 2
---
3 + myVar
}
Example: Scoped to an Array Literal
The following example sets the local variable myVar in a do scope and uses it to set the value of the second element in the array to 2:
%dw 2.0
output application/json
---
do {
var myVar = 2
---
[1, myVar, 3]
}
Example: Scoped to the Object literal
In the following example, references to all the variables are valid. fn and ln are defined and called within the do scope. The global myVar variable is also accessible from that scope.
%dw 2.0
var myVar = 1234
var myDo = do {
var fn = "Annie"
var ln = "Point"
---
{
id : myVar,
firstname : fn,
lastname : ln
}
}
output application/xml
---
{ person : myDo }
<?xml version='1.0' encoding='UTF-8'?>
<person>
<id>1234</id>
<firstname>Annie</firstname>
<lastname>Point</lastname>
</person>
Example: Invalid Reference That Is Outside the Scope
The following example produces an error because fromDoScope is referenced from outside the scope of do. As a consequence, the concatenation operation (++) cannot append the name-value pair to the collection.
%dw 2.0
var myVar = 1234
var myDo = do {
var fn = "Annie"
var ln = "Point"
var fromDoScope = "Platform"
---
{
id : myVar,
firstname : fn,
lastname : ln
}
}
output application/xml
---
{
person : myDo ++ { "outsideDoScope" : fromDoScope }
}
The invalid example returns this error:
Unable to resolve reference of fromDoScope.
Example: Reference That Is Inside a Function
The following example passes the string HELLO to the test function defined in the header. The do scope accepts the string, converts it to lowercase, and then concatenates that string to the suffix variable, which is also defined in the header of the scope.
%dw 2.0
fun test(param1: String) = do {
var suffix = "123"
fun innerTest(str: String) = lower(str)
---
innerTest(param1 ++ suffix)
}
output application/json
---
test("HELLO")
The result is "hello123".