The key word for pattern matching in Scala is match, which is similar to the Java switch but more powerful. Let’s look at several types of pattern matching in Scala.

Constant match

Let’s take a string as an example. The keyword is match, and the case is followed by => to separate the matched pattern from the matched code. Case is each branch, and if the match is successful, the corresponding code block is executed, which can be used without curly braces. If neither match, then the block of code in case _ is executed, relative to the Java default.

val str: String = "b"
val result = str match {
  case "a" => 1
  case "b" => println("b")
    2
  case "c" => 3
  case _ => 0
}
println(result)  // 2

If part b of case changes the following code, it will go to case _ and return 0 because the condition in if does not match.

case "b" if(str.equals("c"))  => println("b")

Type matching

Slightly different from the above, the type is preceded by a parameter that can be referenced later in the code block.

def main(args: Array[String]): Unit = {
    val array: Array[Any] = Array("a", 1, true, Array(1))
    for (e <- array) {
      matchCase(e)
    }
}

def matchCase(v: Any): Unit = {
    v match {
      case a: Int => println(s"Int $a")
      case b: String => println(s"String $b")
      case c: Boolean => println(s"Boolean $c")
      case _ => println(s"Nothing")
    }
}

The running results are as follows:

String a
Int 1
Boolean true
Nothing

An array of matching

def main(args: Array[String]): Unit = { val array: Array[Array[Int]] = Array(Array(1), Array(0, 1), Array(1, 2), Array(1, 2, 3), Array(2, 3, 4)) for (e <- array) { matchArray(e) } } def matchArray(v: Array[Int]): Unit = {v match {case Array(1) => println(v(0)); Y) => println("x+y=" + (x +y)) ") Case Array(1, _*) => println("x") case _ => println(s"Nothing")}

The running results are as follows:

1
x+y=1
x+y=3
x
Nothing

A tuple matching

def main(args: Array[String]): Unit = { val array: Array[Any] = Array((1, 2), (2, 1), (3, 4), (1, 2, 3)) for (e <- array) { matchTuple(e) } } def matchTuple(v: Any): Println (x, 1) println(x, 1) println(x, 1) println(x, 1) println(x, 1) println(x, 1) println(x, 1) println(x, 1) println(x) println(x, 1) println(x, 1) println(x) println(x, 1) println(x) println(x, 1) println(x) println(x) y) => println(s"x = $x, y = $y") case _ => println(s"Nothing") } }

The running results are as follows:

2
2
x = 3, y = 4
Nothing

A collection of matching

The portion of code commented out below is equivalent to his next sentence.

def main(args: Array[String]): Unit = { val list: List[List[Int]] = List(List(0), List(1), List(1, 2), List(1, 2, 3)) for (e <- list) { matchList(e) } } def matchList(v: List[Int]): Unit = {v match {List(1) // case List(1) => println(v(0))) case 1 :: // case List(x, y) => println("x+y=" + (x +y))) case x :: y :: // case List(1, _*) => println(v(0) + "-" + v.tail) case x :: tail => println(x + "-" + tail) case _ => println(s"Nothing") }

The running results are as follows:

0-List()
1
x+y=3
1-List(2, 3)

The object matching

Object matching is to match the value of the object, but in a case it is not possible to create an object by simply calling the apply method of the associated object of Person. It also requires the associated object of Person to declare the unapply method. When the case is compared, he passes the Person object into the unapply method, gets Some, and then matches it against the properties of the object.

def main(args: Array[String]): Unit = { val list: List[Person] = List(" Person ", "Person "," Person ", "Person "," Person ", "Person "," Person ", "Person "," Person ", "Person "," Person ", "Person "," Person ", "Person "," Person ", "Person "," Person ", 28)) for (e <- list) { matchPerson(e) } } def matchPerson(v: Person): Case Person(" name :${v.name}, age :${v.age}") case Person(" name :${v.name}, age :${v.age}") => println(" name :${v.name}, age :${v.age}") ${v.name}, age: ${v.age}") case _ => println(s"Nothing")}} class Person(val name: String, val age: Int) { } object Person { def apply(name: String, age: Int): Person = new Person(name, age) def unapply(person: Person): Option[(String, Int)] = { if (null == person) { None } else { Some(person.name, person.age) } } }

The sample class

If every object had to be matched like this, the code would be tedious. So Scala provides a sample class, keyword case, that can be simplified to the following:

def main(args: Array[String]): Unit = { val list: List[Person2] = List(Person2(Person2, 18), Person2(Person2, 20), Person2(person3), person3 (person3), person3 (person3)) 28)) for (e <- list) { matchPerson(e) } } def matchPerson(v: Person2): Case Person2(Person2, person3) = person3 (person3, person3) The ${v.n ame}, age: ${says v. ge} ") case Person2 (" bill ", 20) = > println (" s name: ${v.name}, age: ${v.age}") case _ = bb0 println(s"Nothing")}} case class Person2(name: String, age: Int)

Person2’s object automatically generates companion objects through the case keyword, and companion objects generate methods such as ToString, Equals, HashCode, and Copy, in addition to the apply and unapply methods above. If applied to a class, the class is multiple.If applied to an object, the class is singleton. We can see that the constructor does not specify whether val or var. It defaults to val.