Pattern Matching with Literal Values

Just like any other programming language, In Mule4, dataweave provides matchfunction to achieve the functionality of if-else statements.

A match expression contains a list of case statements that can optionally have an else statement. Each case statement consists of a conditional selector expression that must evaluate to either true or false.

Pattern matching is another method of flow control, but it does quite a bit more under the hood than the if/else expression does, and the syntax is a little more complicated. Like the if/else expression, pattern matching also returns a single value. Here’s a simplification of how pattern matching expressions are formatted:

Let’s consider a scenario where you need to update certain fields of incoming payload keeping the rest of the fields as it is, you can use a match and case.

match Statement Syntax:

<input_expression> match {
  case <condition> -> <execute_if_condition_pass>
  case <condition> -> <execute_if_condition_pass>
  else -> <execute_if_no_condition_pass>
}
inputExpression match {
  case <condition> -> <routing expression>
  case <condition> -> <routing expression>
  else -> <default routing expression>
}

The easiest way to understand basic pattern matching it to show an example:


Input:

{
  "action": "buy"
}

DW Script:

%dw 2.0
output json
---
payload.action match {
  case "buy"  -> “Buy at market price"
  case "sell" -> "Sell at market price"
  case "hold" -> “Hold asset"
  else   -> "Invalid input"
}

Output:

"Buy at market price"


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