muledataweavemulesoftmule4dynamic-function

Dynamic function call in mule 4


I have multiple functions:

fun testadd(payload) = 
({
addition: payload.value1 as Number + payload.value2 as Number
})

fun testsub(payload) = 
({
substraction: payload.value1 as Number - payload.value2 as Number
})

fun testmultiply(payload) = 
({
multiplication: payload.value1 as Number * payload.value2 as Number
})

I want to call the function dynamically based on the value of "Operation" property/element. suppose if "Operation" = "testadd" then call testadd function, if "Operation" = "testsub" then call testsub function

Input :

{
"value1" : 10,
"value2" : 20,
"Operation" : "testadd"
}

Solution

  • An alternative here is to use function overloading and literal types. For example:

    %dw 2.0
    output json
    
    fun binOp(a, b, op : "add") = a + b
    fun binOp(a, b, op : "sub") = a - b
    fun binOp(a, b, op : "mul") = a * b
    ---
    binOp(10, 20, "add")
    

    DataWeave will call the correct function based on the value of the op parameter.