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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago