Scala Pattern Matching expression with Code Examples

I am sure that if you have come across Java programming language, you might have used switch case statements in Java. Scala pattern matching expression is quite similar with Java switch-case statements, and provides far more features than that.It is one of the widely used expression in Scala language.

So Let’s start learning Scala basic pattern matching expression. Here is the syntax.

The pattern matching expression in above syntax matches value of [expression] with various patterns using case keyword and same as the default keyword in switch-case statement in Java. If no pattern seems to be matched it executes expression for case _ => which eventually matches all expressions.

Let’s take have a simple example of matching value,

Now if we execute it, below will be the output.

And yes, as pattern matching is an expression it returns a value same as if-else expression in Scala, which means you can also assign this expression as a value to a variable or can return from the function.

Following is the example,

In above example, final value after evaluation of match expression will be assigned to the variable errorMessage.Following are the possible constructs which you can use in Patterns Matching Expression in Scala,

References

http://docs.scala-lang.org/tutorials/tour/pattern-matching.html