Named Functions

Named Function

We create functions in the declarations section of the script using the fun keyword. This associates a set of functionality with a name.

To define a Named function in DataWeave use the following syntax:

fun <function_name&gt;(<arg1&gt;, <arg2&gt;, …, <argN&gt;) = <body&gt;

You can call functions with the following syntax:

<function_name&gt;(<arg1&gt;, <arg2&gt;, …, <argN&gt;)

DW Script:

%dw 2.0
output json

fun add(n, m) =
  n + m
---
add(1,2)

Output:

3

 

Notice that there is no return keyword. A return keyword isn’t needed because most everything in DataWeave is an expression, and all expressions return data.

It is often useful to create a scope for functions, where we can declare variables and even more functions. Scopes are created using the do statement and work by making everything defined on its header available for use on its body but not beyond that limit.

In the example below, the diff function uses a scope to define two variables available only to the function itself:


DW Script:

%dw 2.0
output json

fun diff(n) = do {
  var start = n[0]
  var end = n[-1]
  ---
  end - start
}

---
diff([1990, 1995, 2002, 2008, 2021])

Output:

31

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