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

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 days ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago