📜  斯卡拉 |模式匹配

📅  最后修改于: 2022-05-13 01:55:18.937000             🧑  作者: Mango

斯卡拉 |模式匹配

模式匹配是一种检查给定标记序列是否存在特定模式的方法。它是 Scala 中使用最广泛的特性。它是一种根据模式检查值的技术。它类似于 Java 和CJava语句

这里使用“ match ”关键字代替switch语句。 “匹配”总是在 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,因此将对案例 1进行评估。 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 子句。
  • 最后一个“ _ ”是一个“包罗万象”的案例,如果没有一个案例匹配,将被执行。案例也称为替代品
  • 模式匹配没有任何 break 语句。
  • 模式匹配总是返回一些值。
  • 匹配块是表达式,而不是语句。这意味着他们评估任何匹配的案例的主体。这是函数式编程的一个非常重要的特性。
  • 模式匹配也可以用于赋值和理解,不仅在匹配块中。
  • 模式匹配允许使用第一个匹配策略匹配任何类型的数据。
  • 每个 case 语句都返回一个值,整个 match 语句实际上是一个返回匹配值的函数。
  • 可以使用“ | ”在一行中测试多个值。 “。