8.38. Scala pattern matching

发布时间 :2023-11-21 23:00:02 UTC      

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:

8.38.1. 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:

8.38.2. 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:

8.38.3. 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 toString equals hashCode and copy methods, unless the definition of these methods is shown.

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.