Pattern Matching
Using match
Syntax
An Example
Pattern Matching
Pattern matching means exactly what you think it might—checking if an object or series of tokens match a specified pattern. A pattern match consists of a list of alternative cases which are made up of a pattern and a corresponding expression.
Using match
In Scala, pattern matching is done using the match expression. It is evaluated by taking the object to be matched and comparing it with each pattern in the order they are listed. The first pattern to match the object expression is selected and the corresponding expression is evaluated.
Syntax
selector is our object to be matched with the list of alternative patterns. Each case consists of a pattern followed by => which is further followed by an expression to be evaluated if its corresponding pattern is selected.
An Example
Let’s look at an example where given a food item, match matches it to its companion food.
The code below, requires you to insert an input, the method of which has been discussed in a previous lesson.