Search

Dark theme | Light theme

March 14, 2022

DataWeave Delight: Importing Functions With An Alias

When we want to reference functions from other modules than the dw::Core module we must us the import statement. We can use the as keyword to map a function name that we want to import to another name that we want to use in our DataWeave code. We provide an alias for the function that we can use in our code. This could be useful if we think our code gets more readable in a certain context by using different function names, but still want to use the original function implementation. Next to providing an alias for function names, we can also provide an alias for a module name, when we use the import <ModuleName> as <NewModuleName> statement. In our DataWeave code we can then refer to the new alias to call functions from the module.

In the following example code we use import using as to define aliases for functions and a module:

Source

%dw 2.0

// Use an alias for functions.
import upper as upperCase from dw::Core
import firstWith as findFirst from dw::core::Arrays

// Assign an alias to a module, so we can reference
// functions from the module as Str::<function>
import dw::core::Strings as Str

output application/json
---
{
    // Use alias upperCase for upper function.
    upperCase: upperCase("DataWeave"),

    // Use alias findFirst for firstWith function.
    findFirst: [1, 2, 3, 4, 5] findFirst ((item, index) -> item > 3),

    // Use function from module with alias.
    str: Str::reverse("DataWeave")
} 

Output

{
  "upperCase": "DATAWEAVE",
  "findFirst": 4,
  "str": "evaeWataD"
}

Written with DataWeave 2.4.