Lambdas Function

In DataWeave, functions and lambdas (anonymous functions) can be passed as values or be assigned to variables.

DataWeave provides multiple ways to create functions. Just like we have named functions, we have functions without names, called lambdas. A lambda is a value in DataWeave, just like a String, an Object, and a Boolean. When using lambdas within the body of a DataWeave file in conjunction with a function such as map, its attributes can either be explicitly named or left anonymous, in which case they can be referenced as $, $$, etc.

The lambdas function syntax:

<function_name>(<arg1>, <arg2>, …, <argN>)

Examples:

DW Script

%dw 2.0
output json
---
(() -> 2 + 3)()

Output

5

You can define a function as a variable with a constant directive through var Input

{
  "field1": "Annie",
  "field2": "Point",
  "field3": "Stuff"
}

Transform

%dw 2.0
output application/json
var toUser = (user) -> {
  firstName: user.field1,
  lastName: user.field2
}
---
{
  "user" : toUser(payload)
}

Output

{
  "user": {
    "firstName": "Annie",
    "lastName": "Point"
  }
}

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