Open In App

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.



Example 1:




// Scala program to illustrate 
// the pattern matching
  
object GeeksforGeeks {
      
      // main method
      def main(args: Array[String]) {
        
      // calling test method
      println(test(1));
      }
  
  
   // method containing match keyword
   def test(x:Int): String = x match {
         
       // if value of x is 0,
       // this case will be executed
       case 0 => "Hello, Geeks!!"
         
       // if value of x is 1, 
       // this case will be executed
       case 1 => "Are you learning Scala?"
         
       // if x doesnt match any sequence,
       // then this case will be executed
       case _ => "Good Luck!!"
   }
}

Output:



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.

Example 2:




// Scala program to illustrate 
// the pattern matching
   
object GeeksforGeeks {
       
      // main method
      def main(args: Array[String]) {
         
      // calling test method
      println(test("Geeks"));
      }
   
   
   // method containing match keyword
   def test(x:String): String = x match {
          
       // if value of x is "G1",
       // this case will be executed
       case "G1" => "GFG"
          
       // if value of x is "G2", 
       // this case will be executed
       case "G2" => "Scala Tutorials"
          
       // if x doesnt match any sequence,
       // then this case will be executed
       case _ => "Default Case Executed"
   }
}

Output:

Default Case Executed

Important Points:


Article Tags :