Defining and using variables in DataWeave 2.0 (Mule 4)

  • December 15, 2020

DataWeave is the MuleSoft expression language for accessing and transforming data that travels through a Mule app. DataWeave is tightly integrated with the Mule runtime engine, which runs the scripts and expressions in your Mule app.

DataWeave is a functional language in which variables behave just like functions. The general format of a DataWeave script contains three sections: Header, delimiter and body — as shown below.

Variables in DataWeave

Defining and using global variables

You can create a global variable in the header using var directive. Give it a name and assign either a constant value or a lambda expression. You can reference global variables by their name from anywhere in the body of the DataWeave script. 

Here’s an example that initializes three global variables.

Variables in DataWeave1
  • The first one — “mname” — is assigned the literal string value “the”
  • The second one — “mname2” — is assigned a lambda expression that returns a literal string value “other”
  • The third one — “lname” — is assigned a lambda expression that takes a string as an input, passes it to the upper function and returns the string in uppercase 

DataWeave also provides an alternate way to define a variable as a function in a syntax like traditional functions. It may be easier to read for some people. You must use the fun directive in this way.

The following example shows the original syntax for defining lname, as in the previous example, and the alternative using the fun directive. The behavior is identical in both cases.

Variables in DataWeave2

Defining and using local variables

Local variables are initialized inside the body of the DataWeave script using the keyword “using” with the syntax using(<variable-name> =<expression>).

Local variables can only be referenced from within the scope of the expression where they’re initialized. You can declare multiple local variables in a “do” scope header with the syntax do {<variable declaration header> — <body>}. 

Here’s an example of creating a local variable with “do” scope.

Variables in DataWeave3
  • In the first example, a local variable called “name” is declared, then used as a transformation expression 
  • The second example defines two local variables — “fname” and “lname” — in an outer scope and two local variables — “user” and “color” — in an inner scope; it shows that the inner scope can reference the variable in the outer scope by assigning “fname” to “user” 
  • The third example is like the second but shows that the outer scope cannot reference the variable defined in the inner scope when it tries to assign color value to a color property; this results in an error

This is how you define and use global and local variables using DataWeave 2.0 in Mule 4.

— By Sanket Kangle