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

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

4 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

5 months ago

Select a Random Element from a Stream

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

5 months ago

Estimate π Using Monte Carlo Method

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

5 months ago