Latest web development tutorials

Scala pattern matching

Scala provides a powerful pattern matching mechanism, is also widely used.

A matching pattern contains a series of alternatives, each of which begins with a keywordcase.Each contains a backup option and a pattern to a plurality of expressions. Arrow symbol=> separates the patterns and expressions.

The following is a simple pattern matching integer value Example:

object Test {
   def main(args: Array[String]) {
      println(matchTest(3))

   }
   def matchTest(x: Int): String = x match {
      case 1 => "one"
      case 2 => "two"
      case _ => "many"
   }
}

Implementation of the above code, the output is:

$ scalac Test.scala 
$ scala Test
many

match the corresponding Java in the switch, but written after the selector expression.Namely: Selector match {alternatives}.

By order of expressions to match the code written to try each mode to complete the calculation, if they find there is a matching case, matching the rest of the case will not continue.

Next we look at a different data type of pattern matching:

object Test {
   def main(args: Array[String]) {
      println(matchTest("two"))
      println(matchTest("test"))
      println(matchTest(1))
      println(matchTest(6))

   }
   def matchTest(x: Any): Any = x match {
      case 1 => "one"
      case "two" => 2
      case y: Int => "scala.Int"
      case _ => "many"
   }
}

Implementation of the above code, the output is:

$ scalac Test.scala 
$ scala Test
2
many
one
scala.Int

Examples of the first case corresponds to an integer value of 1, the second case corresponds to the string value of two, the second case corresponds to the string value of two, the third case corresponds to the type of model used to determine whether the value passed in whole type, use isInstanceOf compared to determine the type, pattern matching is better. The fourth case indicates the default full-match alternatives, that match is not found in the other match, a similar switch in default.


Use Sample Class

Use the keyword case is the class definition is a sample class (case classes), sample class is a special class, optimized for pattern matching.

The following is a simple example of a sample class:

object Test {
   def main(args: Array[String]) {
   	val alice = new Person("Alice", 25)
	val bob = new Person("Bob", 32)
   	val charlie = new Person("Charlie", 32)
   
    for (person <- List(alice, bob, charlie)) {
    	person match {
            case Person("Alice", 25) => println("Hi Alice!")
            case Person("Bob", 32) => println("Hi Bob!")
            case Person(name, age) =>
               println("Age: " + age + " year, name: " + name + "?")
         }
      }
   }
   // 样例类
   case class Person(name: String, age: Int)
}

Implementation of the above code, the output is:

$ scalac Test.scala 
$ scala Test
Hi Alice!
Hi Bob!
Age: 32 year, name: Charlie?

When you declare a class example, the following procedure occurs automatically:

  • Each parameter constructor are becoming val, unless explicitly declared as var, but that is not recommended;
  • Providing apply methods associated objects, so you can build objects can not use the new keyword;
  • Provided unapply method enables pattern matching can work;
  • Generate toString, equals, hashCode and copy method, unless the display shows definitions for those methods.