Scala pattern matching


Release date:2023-11-22 Update date:2023-11-22 Editor:admin View counts:255

Label:

Scala pattern matching

Scala provides a powerful pattern matching mechanism and has a wide range ofapplications.

A pattern match contains a series of alternatives, each starting with a keyword case . Each alternative contains a pattern and one or more expressions. The arrow symbol => patterns and expressions are separated.

The following is a simple example of integer value pattern matching:

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

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
many

Match corresponds to switch in Java, but is written after the selector expression. Namely: selector match {alternative}.

match expressions are evaluated by trying each pattern in the order in which they are written, as long as a matching case , the rest. case will not continue to match.

Next, let’s look at a pattern matching of different data types:

Example

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, and the output is as follows:

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

The first in the instance case corresponding to the integer value 1, the second case , the corresponding string value two, the third case .The corresponding type pattern, which is used to determine whether the passed value is an integer, compared to using the isInstanceOf to determine the type, it is better to use pattern matching. The fourth case indicates the default full-match option, that is, if no other matchis found, similar to switch in default .

Use sample classes

The class definition that uses the case keyword is the case classes, which is a special class that is optimized for pattern matching.

The following is a simple example of the sample class:

Example

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, and the output is as follows:

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

The following process occurs automatically when the sample class is declared:

  • Each parameter of the constructor becomes val unless explicitly declared as var , but this is not recommended

  • Provided in the companion object apply method, so you don’t have to use the new keyword to build an object

  • Provide unapply method to make pattern matching work

  • Generate toStringequalshashCode and copy methods, unless the definition of these methods is shown.

Powered by TorCMS (https://github.com/bukun/TorCMS).