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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago