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.

[expression] match {
    case [pattern 1] => [expression 1]
    case [pattern 2] => [expression 2]
    ...
    case [pattern N] => [expression N]
    case _ => [expression for default case]
}

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,

//Function for checking error code
// 1: means Successful 
// 0: means Execption
// -1: means Error
// Else no definition found 
def checkErrorCode(code: Int) = code match {
    case 1 => "Execution was successful"
    case 0 => "Execution terminated with Exception"
    case -1 => "Execution terminated with Error"
    case _ => "No code definition found"
}

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

scala> checkErrorCode(0)
res0: java.lang.String = Execution terminated with Exception

scala> checkErrorCode(-5)
res1: java.lang.String = No code definition found

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,

scala> var executionCode = 0
executionCode: Int = 0

scala> var errorMessage = executionCode match {
     | case 1 => "Execution was successful"
     | case 0 => "Execution terminated with Exception"
     | case -1 => "Execution terminated with Error"
     | case _ => "No code definition found"
     | }
errorMessage: java.lang.String = Execution terminated with Exception

scala> println (errorMessage)
Execution terminated with Exception

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>