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>(<arg1>, <arg2>, …, <argN>) = <body>
You can call functions with the following syntax:
<function_name>(<arg1>, <arg2>, …, <argN>)
%dw 2.0 output json fun add(n, m) = n + m --- add(1,2)
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 2.0 output json fun diff(n) = do { var start = n[0] var end = n[-1] --- end - start } --- diff([1990, 1995, 2002, 2008, 2021])
31
If you like my post please follow me to read my latest post on programming and technology.
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…