[Scala process control] 10. Switch statement pattern matching in Scala

insert image description here

In Scala, there are no switchstraightforward constructs like statements in traditional programming languages ​​such as Java or C/C++. The alternative in Scala is to use matchexpressions, which provide more powerful and flexible pattern matching capabilities. matchExpressions can be used to execute different blocks of code based on different conditions.

A simple application of pattern matching is as a replacement for multi-level if-else statements, which can improve code readability. Pattern matching does not use the keyword switch, Scala uses the keyword match. Each possible match is handled by the keyword case. If a case is matched, the code to the right of the right arrow is executed. The underscore _ represents the default case. If none of the preceding cases match, the code of the default case will be executed. Unlike switch statements, the code after each case does not require a break statement. Only matching cases will be executed. Also, the code to the right of each => is an expression that returns a value. Thus, a pattern matching statement is itself an expression that returns a value.

1. Pattern matching

matchThe basic syntax of an expression is as follows:

val variable = ... // 要匹配的变量或表达式
variable match {
    
    
  case pattern1 => // 匹配pattern1时执行的代码块
  case pattern2 => // 匹配pattern2时执行的代码块
  // more cases...
  case _ => // 默认情况,用于处理其他未匹配的情况
}

in:

  • variableis the variable or expression to match against.
  • case pattern1 =>Is a pattern match, used to match a specific condition, and execute the corresponding code block when the match is successful. If variablethere is a match pattern1, the corresponding code block is executed.
  • There can be multiple casestatements, each matching a different pattern.
  • case _ =>is a default case that handles all other unmatched cases. Similar to the case switchin the statement default.

Two, case statement single condition matching

Example:

val x = 2
val result = x match {
    
    
  case 1 => "One"
  case 2 => "Two"
  case 3 => "Three"
  case _ => "Other"
}

println(result) // 输出:"Two"

In the above example, matchthe expression xis pattern matched against the value of the variable, and if xmatched case 2 =>, the string "Two" is returned.

Three, the case statement matches multiple conditions

In Scala matchexpressions, you can use casematch multiple conditions, which can casehandle multiple situations in one statement. You can use commas ,to separate multiple patterns, and casehandle the matching of these patterns in a code block at the same time.

Examples are as follows:

scalaCopy codeval x = 2
val result = x match {
  case 1 | 2 | 3 => "One, Two or Three" // 使用 | 分隔多个条件
  case 4 | 5 | 6 => "Four, Five or Six"
  case _ => "Other"
}

println(result) // 输出:"One, Two or Three"

In the above example, case 1 | 2 | 3 =>it means to split the pattern matching into three conditions: 1, 2, and 3. If xthe value is 1, 2 or 3, the corresponding code block will be executed.

Four, with if

In addition to using |operators to join multiple conditions, you can use conditions to perform more complex filtering on multiple conditions in the ifsame statement.case

matchExpressions can also be combined with ifconditions for more complex pattern matching, and can also match complex data structures, such as sets, tuples, etc.

val y = (1, 2)
val message = y match {
    
    
  case (1, 2) => "Tuple with (1, 2)"
  case (a, b) if a > b => "First element is greater than second element"
  case (a, b) if a < b => "First element is less than second element"
  case _ => "Other"
}

println(message) // 输出:"Tuple with (1, 2)"

In the above example, matchthe expression matches a tuple (1, 2)and returns the corresponding message. ifConditions are used to further filter matching tuples.

In general, matchexpressions are switcha powerful pattern-matching tool for replacing statements in Scala. It provides more flexibility and expressiveness when dealing with complex conditions and multiple situations.

5. Match collection type

In Scala matchexpressions, you can use casematching collection types, including List, Array, Seqand so on. Statements can be used caseto match different elements and structures of collections and execute corresponding code blocks in different matching situations.

Examples are as follows:

val myList = List(1, 2, 3)

val result = myList match {
    
    
  case List(1, 2, 3) => "List contains 1, 2, and 3 in order"
  case List(a, b, c) => s"List contains elements: $a, $b, $c"
  case List(_, _, _) => "List contains three elements, but not 1, 2, 3 in order"
  case Nil => "Empty list"
  case _ => "Other"
}

println(result) // 输出:"List contains 1, 2, and 3 in order"

In the above example, myLista Listcollection of types. matchExpressions use casestatements to match different aggregate cases. List(1, 2, 3)Used to match a sequential list containing 1, 2, and 3. List(a, b, c)Used to match a list containing any three elements and bind it to a variable a, band c, for use in subsequent code blocks. List(_, _, _)Used to match a list containing any three elements, regardless of the specific value of the element.

In addition List, matchexpressions can also be used to match other collection types, such as Array, Seqetc. Here is Arrayan example of a match type:

val myArray = Array(1, 2, 3)

val result = myArray match {
    
    
  case Array(1, 2, 3) => "Array contains 1, 2, and 3 in order"
  case Array(a, b, c) => s"Array contains elements: $a, $b, $c"
  case Array(_, _, _) => "Array contains three elements, but not 1, 2, 3 in order"
  case Array() => "Empty array"
  case _ => "Other"
}

println(result) // 输出:"Array contains 1, 2, and 3 in order"

In the above example, myArrayis a Arraycollection of types, matchthe expressions use casestatements to match different array situations.

By using casematching collection types, matchdifferent collection cases can be handled in expressions, making the code more flexible and readable.

Guess you like

Origin blog.csdn.net/m0_47256162/article/details/132159551