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



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])



Follow Me

If you like my post please follow me to read my latest post on programming and technology.



Leave a Reply

Your email address will not be published. Required fields are marked *