Contact Us 1-800-596-4880

Work with Functions and Lambdas in DataWeave

DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

In DataWeave, functions and lambdas (anonymous functions) can be passed as values or be assigned to variables. Before you begin, note that DataWeave version 2 is for Mule 4 apps. For a Mule 3 app, refer to the DataWeave 1.0 documentation set in the Mule 3.9 documentation. For other Mule versions, you can use the version selector for the Mule Runtime table of contents.

When using lambdas within the body of a DataWeave file in conjunction with an function such as map, its attributes can either be explicitly named or left anonymous, in which case they can be referenced as $, $$, etc.

Declare and Invoke a Function

You can declare a function in the header or body of a DataWeave script by using the fun keyword. Then you can invoke the function at any point in the body of the script.

You refer to functions using this form: functionName() or functionName(arg1, arg2, argN)

You can pass an expression in between the parentheses for each argument. Each expression between the parentheses is evaluated, and the result is passed as an argument used in the execution of the function body.

Input
{
  "field1": "Annie",
  "field2": "Point",
  "field3": "Stuff"
}
Transform
%dw 2.0
output application/json
fun toUser(obj) = {
  firstName: obj.field1,
  lastName: obj.field2
}
---
{
  "user" : toUser(payload)
}
Output
{
  "user": {
    "firstName": "Annie",
    "lastName": "Point"
  }
}

Assign a Lambda to a Var

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"
  }
}

Use Named Parameters in a Lambda

This example uses a lambda with an attribute that is explicitly named as name.

Input
%dw 2.0
output application/json
var names = ["john", "peter", "matt"]
---
users: names map((name) -> upper(name))
Transform
{
  "users": ["JOHN","PETER","MATT"]
}

Use Anonymous Parameters in a Lambda

This example uses a lambda with an attribute that’s not explicitly named, and so is referred to by default as $.

Transform
%dw 2.0
output application/json
var names = ["john", "peter", "matt"]
---
users: names map upper($)
Output
{
  "users": ["JOHN","PETER","MATT"]
}