Scala Tutorial Scala References

Scala - Match Expression



Scala has a concept of a match expression. In the most simple case it can be used like a Java match statement. The syntax for using match expression is given below:

Syntax

expression match {
  case 1 => 
      statement 1
  case 2 =>
     statement 2
     ...
     ...
     ...
  case N =>
     statement N
  // default case 
  case _ =>
     default statement
} 

The expression is evaluated and matched with the cases. When the case matches, the following block of code is executed. If no case matches with expression, the default code block gets executed.

Example:

In the example below, a variable called i with value 2 is matched against case values. When the case value matches with expression value, the following block of code gets executed.

object MainObject {
  def main(args: Array[String]) {
    var i = 2
    i match {
      case 1 => println("Red")
      case 2 => println("Blue")
      case 3 => println("Green")
    }  
  }
}

The output of the above code will be:

Blue

default case

In Scala, the default case starts with case _ followed by => and default code block. The default code block gets executed when the expression value do not match with any test cases.

Example:

In the example below, a variable called i with value 10 is matched against case values. As there is no case that matches with value 10, hence default block of code gets executed.

object MainObject {
  def main(args: Array[String]) {
    var i = 10
    i match {
      case 1 => println("Red")
      case 2 => println("Blue")
      case 3 => println("Green")
      case _ => println("No match found.")
    }  
  }
}

The output of the above code will be:

No match found.

Common code blocks

There are instances where same code block is required in multiple cases.

Example:

In the example below, same code block is shared for different match cases.

object MainObject {
  def main(args: Array[String]) {
    var i = 10
    i match {
      case 1 => println("Red")
      case 2 | 10 => println("Blue")
      case 3 | 4 | 5 => println("Green")
      case _ => println("No match found.")
    }  
  }
}

The output of the above code will be:

Blue

Using if expressions in case statements

Scala gives the flexibility of using if expressions in case statements which can be used for pattern matching.

Example:

In the example below, the second, third and fourth case statements, all use if expressions to match ranges of numbers.

object MainObject {
  def main(args: Array[String]) {
    var i = 50
    i match {
      case 1 => println("Red")
      case i if i == 2 || i == 10 => println("Blue")
      case i if 3 to 5 contains i => println("Green")
      case i if i > 10 => println("Yellow")
      case _ => println("No match found.")
    }  
  }
}

The output of the above code will be:

Yellow

Using Any type

Scala gives the flexibility of using Any type with the case statements which provides great support for pattern matching.

Example:

In the example below, any type of argument is used at the same time with the match expression.

object MainObject {
  def matchTest(i: Any): Any = i match {
    case 1 => "Red"
    case i if i == 2 || i == 10 => "Blue"
    case i if 3 to 5 contains i => "Green"
    case "Y" => 1
    case "N" => 0
    case "LON" => "London"
    case "MUM" => "Mumbai"    
    case _ => "No match found"
  }  

  def main(args: Array[String]) {
    println("matchTest(20) = " + matchTest(20))
    println("matchTest(10) = " + matchTest(10))
    println("matchTest(\"Y\") = " + matchTest("Y"))
    println("matchTest(\"LON\") = " + matchTest("LON"))
  }
}

The output of the above code will be:

matchTest(20) = No match found
matchTest(10) = Blue
matchTest("Y") = 1
matchTest("LON") = London

Using case Classes

The case classes are special classes that are used in pattern matching with case expressions. These can be considered as standard classes with a special modifier: case.

Example:

Consider the example below where case class is used for pattern matching.

object MainObject {
  //case class
  case class Person(name: String, age: Int)

  //match function
  def matchPerson(p: Person) = p match {
    case Person("John", 25) => "Hi John"
    case Person("Marry", 27) => "Hi Marry"
    case Person(name, age) => 
      "Data is not found for: " + name + ", " + age + " years old"
  }  

  def main(args: Array[String]) {
    val p1 = new Person("John", 25)
    val p2 = new Person("Marry", 27)
    val p3 = new Person("Kim", 25)

    println(matchPerson(p1))
    println(matchPerson(p2))
    println(matchPerson(p3))
  }
}

The output of the above code will be:

Hi John
Hi Marry
Data is not found for: Kim, 25 years old