Scala Match Case: Matching Multiple Values
In Scala, you can combine multiple values together to form a matching pattern using a comma. For example:
val x = 2
x match {
case 1 | 2 | 3 => println('x is 1, 2, or 3')
case _ => println('x is something else')
}
In the above code, the matching pattern 1 | 2 | 3 means that if the value of x is 1, 2, or 3, then the code block in the first case statement will be executed. If the value of x is not 1, 2, or 3, then the code block in the next case statement will be executed.
Besides using comma-separated multiple values, you can also use case Seq() to match against a sequence of multiple values. For example:
val x = List(1, 2, 3)
x match {
case Seq(1, 2, 3) => println('x is a list of 1, 2, and 3')
case _ => println('x is something else')
}
In the above code, the matching pattern Seq(1, 2, 3) means that if x is a list containing 1, 2, and 3, then the code block in the first case statement will be executed. If x is not such a list, then the code block in the next case statement will be executed.
原文地址: https://www.cveoy.top/t/topic/oA6z 著作权归作者所有。请勿转载和采集!