Contact Free trial Login

Define DataWeave Functions

You can define your own DataWeave functions using the fun declaration in the header of a DataWeave script. Before you begin, note that DataWeave 2.0 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.

In this simple example, a DataWeave function accepts a single String argument that outputs "HELLO":

%dw 2.0
output application/json
fun toUpper(aString) = upper(aString)
---
toUpper("hello")

The argument to a DataWeave function can be any DataWeave expression. This function also outputs "HELLO":

%dw 2.0
output application/json
fun toUpper(aString) = upper(aString)
---
toUpper("h" ++ "el" ++ lower("LO") )

To test the type of the argument passed into your function, you can perform pattern matching with the built-in match operation.

Example: Function that Uses Pattern Matching
%dw 2.0
output application/json
fun toUpper(aString)
= aString match {
  case is String -> upper(aString)
  else -> null
}
---
toUpper("h" ++ "el" ++ lower("LO") )

This example creates a function that reformats a numeric string into a common phone number format:

Example: toPhoneFormat() Function
%dw 2.0
output application/json
fun toPhoneFormat(str: String) =
    "(" ++ str[0 to 2] ++ ") " ++ str[3 to 5] ++ "-" ++ str[6 to 9]
---
toPhoneFormat("1234567890")
Output of toPhoneFormat("1234567890")
"(123) 456-7890"

Overloading Functions

DataWeave enables you to create multiple functions with the same name but different parameters. This feature is useful for defining different behaviors based on the arguments of a function call.

Parameters in overloaded functions differ in number or type. To understand more about defining type constraints on function parameters, see Type System.

DataWeave uses the first function it finds that accepts the arguments of the function call, based on the order in which the functions are declared in the script.

Example: Function that Uses Function Overloading
%dw 2.0
output application/json

fun toUpper(a: String) = upper(a)
fun toUpper(a: Any) = null
fun toUpper(a: String, b: Number) = upper(a) ++ b as String
---
toUpper("hi!")

The argument of the function call toUpper("hi!") matches the types String and Any, so it is possible to call the function with the first two definitions. However, DataWeave executes the function fun toUpper(a: String) = upper(a) because that function is defined before the one that uses the type Any.

Output of toUpper("hi!")
"HI!"
Output of toUpper(true)
null
Output of toUpper("age: ", 26)
"AGE: 26"

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub