case class 模式匹配 :
class A case class A1(name:String,age:Int) extends A case class A2(name:String,address:String) extends A def classMatch(c:A){ c match { case A1(name,age) => println("类型是A1") case A2(name,address) => println("类型是A2") case _ => println("类型未知") } }
list列表匹配(Nil代表结束,tail代表未知的后续元素):
def listMatch(list:Any)={ list match { case e1::e2::Nil => println("list仅有2个元素:"+e1+e2) case "abc"::"678"::"mmm"::Nil => println("list仅仅包含3个固定元素") case 0::tail => println("list以0开头包含"+(list.asInstanceOf[List[Int]]).length+"个元素") case 0::Nil => println("这个list仅仅包含0") case _ => println("没有匹配") } }
数组模式匹配:
def arrayMatch(arr:Any)={ arr match { case Array("abc") => println("only one abc") case Array("abc",1) => println("两个元素:abc和1") case Array(a,b) => println("两个动态元素:"+a+"-"+b) case Array(0,_*) => println("这个array以0开头元素个数不计:"+arr) case _ => println("没有匹配") } }
类型模式匹配:
//传入的参数,但判断类型时实际使用的是isInstanceOf[xxx] def getNum(item:Any)={ item match{ case x:String => print("String") case i:Int => print("Int") case c:Char => print("Char") case _=>0//这个是完全没有匹配上的情况 } }
值匹配:
def testMatch(i:Int,s:String="default"):Unit={ i match { case 1 => print("数字:"+1) case 2 => print("数字:"+2) case 3 => print("数字:"+3) case 5 if(s equals "mz") => print("数字:"+3+"mz")//匹配后仍可添加判断 case tmp1 => print("tmp1的赋值数字:"+tmp1)//会将i赋值给tmp1变量 case _ => print("其它喽") } }