一:普通的模式匹配
1.概述
2.程序示例(普通的示例)
1 package ty 2 3 object MatchCaseTest { 4 def main(args: Array[String]): Unit = { 5 judgeGrade("B") 6 } 7 def judgeGrade(grade:String): Unit ={ 8 grade match { 9 case "A"=>println("Excellent") 10 case "B"=>println("Good") 11 case "C"=>println("so") 12 case _=>println("bad") 13 } 14 } 15 }
3.效果
4.if守卫
1 package ty 2 3 object MatchCaseTest { 4 def main(args: Array[String]): Unit = { 5 judgeGrade("B","tom") 6 judgeGrade("E","tom") 7 } 8 def judgeGrade(grade:String,name:String ): Unit ={ 9 grade match { 10 case "A"=>println("Excellent") 11 case "B"=>println("Good") 12 case "C"=>println("so") 13 case _ if name=="tom"=>println("very good") 14 case _=>println("bad") 15 } 16 } 17 }
5.效果
二:Array模式匹配
1.模式匹配(Array)
2.程序示例(Array)
1 package ty 2 3 object ArrayMatch { 4 def main(args: Array[String]): Unit = { 5 judge(Array("x1")) 6 judge(Array("X2","X3","X4")) 7 judge(Array("caojun","ui")) 8 } 9 def judge(arr:Array[String]): Unit ={ 10 arr match { 11 //完全匹配 12 case Array("x1")=>println("x1") 13 //个数匹配 14 case Array(a,b,c)=>println(a,b,c) 15 //某一个元素打头 16 case Array("caojun",_*)=>println("caojun start") 17 case _=>println("======") 18 } 19 } 20 }
3.效果
三:List模式匹配
1.模式匹配(List)
2.程序示例
1 package ty 2 3 object ListMatch { 4 def main(args: Array[String]): Unit = { 5 judge(List("ui")) 6 judge(List("jj","hh","ff")) 7 judge(List("lao","li")) 8 } 9 def judge(list:List[String]): Unit ={ 10 list match { 11 case "ui"::Nil=>println("ui") 12 case b1::b2::b3::Nil=>println(b1+","+b2+","+b3) 13 case "lao"::tail=>println("hi lao start") 14 case _=>println("===") 15 } 16 } 17 }
3.效果
四:遍历与模式匹配结合
1.遍历
1 package ty 2 3 object ForMatch { 4 def main(args: Array[String]): Unit = { 5 "hello world" foreach(c=>println( 6 c match { 7 case ' ' =>"space" 8 case ch =>"Char:"+ch 9 } 10 )) 11 } 12 }
2.效果
五:样例类
1.模式匹配(case class)
2.程序示例(传统)
1 package ty 2 class S(name:String,age:Int){ 3 def say=println("hello") 4 } 5 object S{ 6 def apply(name: String, age: Int): S = new S(name, age) 7 } 8 object TraditionMatch { 9 def main(args: Array[String]): Unit = { 10 var s=S("zahngsan",20) 11 s.say 12 } 13 }
3.效果
4.程序示例(case class)
1 package ty 2 case class R(name:String,age:Int){ 3 def say=println("hi") 4 } 5 object CaseClass { 6 def main(args: Array[String]): Unit = { 7 var r=R("lisi",32) 8 r.say 9 } 10 }
5.效果
六:类模式匹配
1.程序示例,模式匹配(匹配类)
1 package ty 2 3 //定义一个类 4 class Per 5 case class TT(name:String,project:String) extends Per{ 6 7 } 8 case class SS(name:String,room:String) extends Per{ 9 10 } 11 class JudgeClass(){ 12 def judge(per:Per){ 13 per match { 14 case TT(name,project)=>println(name+","+project) 15 case SS(name,room)=>println(name+","+room) 16 case _=>println("===") 17 } 18 } 19 } 20 object ClassMatch { 21 def main(args: Array[String]): Unit = { 22 var t=TT("tom","en") 23 var s=SS("Bob","202") 24 new JudgeClass().judge(t) 25 } 26 }
3.效果