Tuesday, 26 August 2014

Scala Note 21: Pattern Matching


Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy.The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.
  1. The first case has two '_' wildcards, they will match any values of the first two parameters of Person.
  2. 'a' refers to 'p.age'. This case will success when if condition holds.
  3. The second case will success when the first case fails and p.lastname = 'Neward'
  4. The third case is also called 'extractor', which makes the values of 'p' be used in the local variables of the case.
  5. The last case will execute, when all above cases fail.



  1. case class Person(first: String, last: String, age: Int) {  
  2.   println(first);  
  3.   println(last)  
  4.   println(age)  
  5. }
  6. def process(p: Person) =  
  7.     {  
  8.       "Processing " + p + " reveals that" +  
  9.         (p match {  
  10.           case Person(_, _, a) if a > 30 =>  
  11.             " they're certainly old."  
  12.           case Person(_, "Neward", _) =>  
  13.             " they come from good genes...."  
  14.           case Person(first, last, ageInYears) if ageInYears > 17 =>  
  15.             first + " " + last + " is " + ageInYears + " years old."  
  16.           case _ =>  
  17.             " I have no idea what to do with this person"</span>  
  18.         })  
  19.     }  

  20.  def matArray(a: List[Any]) {  
  21.    a match {  
  22.      case 0 :: Nil => { print("an array contains 0 as an element") }  
  23.      case x :: y :: Nil => { print("an array contains only two elements") }  
  24.      case 0 :: tail => { print("an array with head as 0") }  
  25.      case _ =>print("default")  
  26.    }  
  27.  }  

No comments:

Post a Comment