package com.ming.test/** * 模式匹配 */object MatchTest { def main(args: Array[String]): Unit = { //match 基本用法 var sign=3 var m='w' var str='d' var digit="dsafdsafdsaf" m match{ case '+' => sign=10 case '-' => sign=100 case _ => sign=200 } println(sign) sign=m match{ case '+' => 1000;case '-' => 10000;case _ => 1231} println(sign) //带有守卫的匹配 sign=m match{ case '+' => 12;case '-' =>23;case _ if Character.isDigit(m) =>2;case _ => 1000000} println(sign) //类型模式 //var a=obj match{case x:Int=>x;case s : String => Integer.parseInt(s);case _:BigInt=>Int.MaxValue;case _ => 0} //数组匹配 var array=Array(0,2) val s=array match{ case Array(0)=>"0" case Array(x,y)=>x+" "+ y case Array(0,_*)=>"0 ......" case _ =>"something else" } println(s) //匹配列表 val list=List(0,212,3) var lst=list match{ case 0 :: Nil =>"0" case x :: y ::Nil => x+" "+ y case 0 :: tail => "0...." case _ =>"something else" } println(lst) //元祖匹配 val yuanzu=(1,2,0) var zu=yuanzu match{ case (0,_,1) => "0 ..." case (y,0,0) => y+"0" case _ => "neither is 0" } println(zu) //变量中声明中的模式 val (x,y)=(1,2); println(x+y) //for 表达式中的模式 for((k,v)<-Map((1,""),(2,3)) if v !="")println(k+"->"+v) } }