WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Scala pattern matching


Scala provides a powerful pattern matching mechanism and is widely used.

A pattern match contains a series of alternatives,Each starts with a keyword case。Each alternative contains a pattern and one or more expressions。 The arrow symbol => separates the pattern and expression.

The following is a simple example of an integer value pattern match:

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"
   }
}

Execute the above code, the output is:

Execute the above code, the output is:

$ scalac Test.scala
$ scala Test
Many

match corresponds to the switch in Java, but is written after the selector expression. That is: Selector match {option}.

The match expression tries to complete the calculation by trying each pattern in the order in which the code is written. As long as there is a matching case, the remaining cases will not continue to match.

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

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"
   }
}

Execute the above code, the output is:

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

The first case in the instance corresponds to the integer value 1, the second case corresponds to the string value two, and the third case corresponds to the type pattern, which is used to determine whether the passed value is an integer, compared to using isInstanceOf Judging the type, using pattern matching is better. The fourth case represents the default all-matching alternative, that is, no matches are found for other matches, like default in switch.


Use the sample class

The class definitions that use the case keyword are just case classes. The sample class is a special class that is 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 + "?")
         }
      }
   }
   // Sample class
   case class Person(name: String, age: Int)
}

Execute the above code, the output is:

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

When you declare a sample class, the following process happens automatically:

  • Each parameter of the constructor becomes val unless explicitly declared as var, but this is not recommended;
  • The apply method is provided in the companion object, so you can build the object without using the new keyword;
  • Provide unapply methods to make pattern matching work;
  • Generate toString, equals, hashCode, and copy methods unless the definitions for these methods are shown.