Scala 模式匹配
模式匹配是一种检查给定的标记序列是否存在特定模式的方法。它是Scala中使用最广泛的功能。它是一种根据模式来检查数值的技术。它类似于Java和C的switch语句。
在这里, “match “关键字被用来代替switch语句。”match “总是被定义在Scala的根类中,以使其对所有对象都可用。它可以包含一连串的选项。每个选项都从 case 关键字开始。每个case语句包括一个模式和一个或多个表达式,如果指定的模式被匹配,这些表达式将被评估。为了区分模式和表达式,使用了 **箭头符号(= >) **
例1 :
// Scala program to illustrate
// the pattern matching
object GeeksforGeeks {
// main method
def main(args: Array[String]) {
// calling test method
println(test(1));
}
// method containing match keyword
def test(x:Int): String = x match {
// if value of x is 0,
// this case will be executed
case 0 => "Hello, Geeks!!"
// if value of x is 1,
// this case will be executed
case 1 => "Are you learning Scala?"
// if x doesnt match any sequence,
// then this case will be executed
case _ => "Good Luck!!"
}
}
输出
Are you learning Scala?
解释: 在上面的程序中,如果在测试方法调用中传递的x的值与任何一个案例相匹配,那么该案例中的表达式将被评估。这里我们传递的是1,所以case 1将被评估。case_ =>是默认的case,如果x的值不是0或1,将被执行。
例2 :
// Scala program to illustrate
// the pattern matching
object GeeksforGeeks {
// main method
def main(args: Array[String]) {
// calling test method
println(test("Geeks"));
}
// method containing match keyword
def test(x:String): String = x match {
// if value of x is "G1",
// this case will be executed
case "G1" => "GFG"
// if value of x is "G2",
// this case will be executed
case "G2" => "Scala Tutorials"
// if x doesnt match any sequence,
// then this case will be executed
case _ => "Default Case Executed"
}
}
输出
Default Case Executed
重要的一点
- 每个匹配关键词必须至少有一个case子句。
- 最后一个 “_ “,是一个 “万能 “ 的案例,如果没有一个案例匹配,将被执行。案例也被称为替代品。
- 模式匹配没有任何中断语句。
- 模式匹配总是返回一些值。
- 匹配块是表达式,而不是语句。这意味着它们评估任何一个匹配的案例的主体。这是函数式编程的一个非常重要的特点。
- 模式匹配也可以用于赋值和理解,不仅仅是在匹配块中。
- 模式匹配允许用第一个匹配策略匹配任何类型的数据。
- 每个case语句返回一个值,整个匹配语句实际上是一个返回匹配值的函数。
- 通过使用 “| “可以在一行中测试多个值。
极客教程