Variables in DataWeave 2.0 (Mule 4)

Variables 

Variables are a way to store values with a given name so they can be later reused from different parts of your code, making the code cleaner and sometimes even more performant as values are calculated once.

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 3 sections: Header, delimiter, and body as shown in the exhibit below.

There are different ways of declaring and using the variables in data-weave.

  • Global variables are initialized in the header of the DataWeave script and can be referenced by name from anywhere in the body of a DataWeave script.
  • The header of a DataWeave script accepts a var directive that initializes a variable, for example: var string=’USA’. You can declare multiple global variables on separate lines in the header.
  • Local variables are initialized in the body of the DW script and can be referenced by name only from within the scope of the expression where they are initialized.

To set a variable, use the following syntax:

var <var_name> = <expression>

Note: DW variables cannot be reassigned. They are also distinct from variables that are part of the Mule message (such as target variables). variables do not persist beyond the scope of the script in which they are initialized

An expression is something that returns a value, or is a value itself. This value can then be referenced using the variable name. Here’s an example of setting a variable to an explicit value:

DW Script:

%dw 2.0
output json
var max = "Data-weave Variables"
---
max

Output:

"Data-weave Variables"

Variables are almost always declared in the header of the script, where you set other declarations.

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *