多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**1. 基本模式匹配** ```scala val varialbe: String = "salt" varialbe match { case "salt" => println("salt") // salt case "chips" => println("chips") case "eggs" => println("eggs") case _ => println("default") // 相当于Java的default } ``` ```scala def matchTest(x:Int):String = x match { case 1 => "one" case 2 => "two" case _=> "many" } println(matchTest(1)) // one println(matchTest(1000000)) // many ``` ```scala (1,2) match { case (x, _)=>println(x) // 不关心第二个元素 } ``` <br/> **2. 类型匹配** ```scala def matchTest(x:Any):String = x match { case x:Int => "Int" case x:String => "String" case _=> "Any" } println(matchTest(1)) // Int println(matchTest(3.14)) // Any ``` <br/> **3. 构造器模式匹配** ```scala // Student是一个 case class ,这里就不给出了 def matchTest(x:Student) = x match { case Student(name, 19) => println(s"name=$name, age=19") case Student("Tom", age) => println(s"name=Tom, age=$age") case Student(name, age) => println(s"name=$name, age=$age") case _=> println("no matches") } matchTest(Student("Jason", 19)) // name=Jason, age=19 matchTest(Student("Tome", 20)) // name=Tome, age=20 matchTest(Student("Jimmy", 20)) // name=Jimmy, age=20 ``` <br/> **4. 模式守卫** 就是在`case`后面加上`if`条件判断。 ```scala def matchTest(x:Int):String = x match { case i if i==1 => "one" case i if i==2 => "two" case _=> "many" } println(matchTest(3)) // many println(matchTest(1)) // one ``` <br/> **5. 伴生模式匹配** ```scala class Student(var name: String, var age: Int) object Student { def apply(name: String, age: Int): Student = new Student(name, age) def unapply(arg: Student): Option[(String, Int)] = { if (arg == null) None else Some(arg.name, arg.age) } } object HelloWorld { def main(args: Array[String]): Unit = { def matchTest(x: Student) = x match { case Student(name, age) if age <= 20 => println("young man") case Student(name, age) if age > 20 => println("old man") case _ => println("no matches") } matchTest(Student("Jason", 19)) // young man } } ``` <br/> **6. 序列模式** ```scala val expr = List(1, 2, 3) expr match { case List(x, _, _) => println(x) // 1 case _ => println("not found") } expr match { // _* 作为模式的最后元素 case List(1, _*) => println("found it") // found it case _ => println("not found") } ``` <br/> **7. 元组模式** ```scala val expr = (1, 2, 3) expr match { case (a, b, c) => println(a, b, c) // (1,2,3) case _ => println("not found") } ``` <br/> **8. 变量绑定模式** 在上面的序列模式中使用 `_*` 匹配的内容好像被丢弃了,使用变量绑定可以找回来。如果整个模式匹配成功,符合部分模式的部分可以用变量代替。 格式:`变量名 @ 部分模式` ```scala val expr = List(1, 2, 3) expr match { case List(x, tail@_*) => println(x, tail) // (1,List(2, 3)) case _ => println("not found") } ```