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

Minimum Cost to Paint Houses with K Colors

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

1 day ago

Longest Absolute Path in File System Representation

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

3 weeks ago

Efficient Order Log Storage

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

1 month ago

Select a Random Element from a Stream

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

1 month ago

Estimate π Using Monte Carlo Method

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

2 months ago

Longest Substring with K Distinct Characters

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

2 months ago