Article directory
In Scala, there are no switch
straightforward constructs like statements in traditional programming languages such as Java or C/C++. The alternative in Scala is to use match
expressions, which provide more powerful and flexible pattern matching capabilities. match
Expressions 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
match
The basic syntax of an expression is as follows:
val variable = ... // 要匹配的变量或表达式
variable match {
case pattern1 => // 匹配pattern1时执行的代码块
case pattern2 => // 匹配pattern2时执行的代码块
// more cases...
case _ => // 默认情况,用于处理其他未匹配的情况
}
in:
variable
is 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. Ifvariable
there is a matchpattern1
, the corresponding code block is executed.- There can be multiple
case
statements, each matching a different pattern. case _ =>
is a default case that handles all other unmatched cases. Similar to the caseswitch
in the statementdefault
.
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, match
the expression x
is pattern matched against the value of the variable, and if x
matched case 2 =>
, the string "Two" is returned.
Three, the case statement matches multiple conditions
In Scala match
expressions, you can use case
match multiple conditions, which can case
handle multiple situations in one statement. You can use commas ,
to separate multiple patterns, and case
handle 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 x
the 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 if
same statement.case
match
Expressions can also be combined with if
conditions 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, match
the expression matches a tuple (1, 2)
and returns the corresponding message. if
Conditions are used to further filter matching tuples.
In general, match
expressions are switch
a 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 match
expressions, you can use case
matching collection types, including List
, Array
, Seq
and so on. Statements can be used case
to 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, myList
a List
collection of types. match
Expressions use case
statements 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
, b
and 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
, match
expressions can also be used to match other collection types, such as Array
, Seq
etc. Here is Array
an 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, myArray
is a Array
collection of types, match
the expressions use case
statements to match different array situations.
By using case
matching collection types, match
different collection cases can be handled in expressions, making the code more flexible and readable.