Scala | Pattern Matching
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Here, “match” keyword is used instead of switch statement. “match” is always defined in Scala’s root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched. To separate the pattern from the expressions, arrow symbol(=>) is used.
Are you learning Scala?
Explanation: In the above program, if the value of x which is passed in test method call matches any of the cases, the expression within that case is evaluated. Here we are passing 1 so case 1 will be evaluated. case_ => is the default case which will get executed if value of x is not 0 or 1.
Default Case Executed
- Each match keyword must have at least one case clause.
- The last “_“, is a “catch-all” case, will be executed if none of the cases matches. Cases are also called alternatives.
- Pattern matching does not have any break statement.
- Pattern matching always returns some value.
- Match blocks are expressions, not statements. This means that they evaluate the body of whichever case matches. This is a very important feature of functional programming.
- Pattern matching can also be used for value assignment and for comprehension, not only in match block.
- Pattern matching allows matching any sort of data with the first match policy.
- Each case statement returns a value, and the whole match statement is virtually a function that returns a matched value.
- Multiple values can be tested in a single line by using “|“.