1、与java switch类似
package com.cslc.day3 import scala.util.Random object MatchApp { def main(args: Array[String]): Unit = { val names=Array("liu","wang","li") val name=names(Random.nextInt(names.length)) name match { case "liu" => {println("刘老师")} case "wang" => {println("王老师")} case "li" => {println("李老师")} case _=>{println("没有老师")} } } }
2、数组模式匹配
package com.cslc.day3 object MatchApp { def main(args: Array[String]): Unit = { greeting(Array("zhangsan")) greeting(Array("xiaoming","xiaohua")) greeting(Array("xx","ccc","xxx")) greeting(Array("zhangsan","xx","ccc","xxx")) } def greeting(arr:Array[String]): Unit = { arr match { case Array("zhangsan") => {println("this is zhangsan")} case Array(x, y) => {println("hi " + x + " and " + y)} case Array("zhangsan", _*) => {println("zhansan and his friends")} case _ => { println("every body") } } } }
3、列表的模式匹配
package com.cslc.day3 object MatchApp { def main(args: Array[String]): Unit = { greeting(List("zhangsan")) greeting(List("lisi","wangwu")) greeting(List("zhangsan","lisi","xxx")) greeting(List("lisi","zhangsan","zhaopliu")) } def greeting(l:List[String]):Unit={ l match{ case "zhangsan"::Nil =>{println("this is zhangsan ")} case x::y::z::Nil=>{println("hell "+x+" and "+y)} case "zhangsan"::tail=>{println("zhangsan and his friends")} case _ => {println("hello every body")} } } }
4、类型的模式匹配
package com.cslc.day3 import scala.collection.mutable.ListBuffer object MatchApp { def main(args: Array[String]): Unit = { matchup("1") matchup(1) matchup(Map("xxx"->"xxxs")) matchup(obj=List("xxx")) } def matchup(obj:Any): Unit ={ obj match{ case x:Int=>{println("Int: "+x)} case x:String=>{println("String" +x)} case x:Map[_,_] =>{x.foreach(println)} case _ => {println("other type")} } } }
5、异常处理
package com.cslc.day3 import scala.collection.mutable.ListBuffer object MatchApp { def main(args: Array[String]): Unit = { try{ val i=10/0 println(i) }catch { case e:ArithmeticException =>{println(e.getCause+e.getMessage)} case e:Exception =>{println("error")} }finally { println("xxx") } } }
6、case class模式匹配
package com.cslc.day3 import scala.collection.mutable.ListBuffer object MatchApp { def caseclassMatch(person: Person): Unit ={ person match{ case CTO(name,floor)=>{println(name +"is working at "+floor)} case Empolyee(name)=>{println(name +"working at all floor")} case Other(name)=>{println(name +" is only enter one floor")} } } def main(args: Array[String]): Unit = { caseclassMatch(CTO("bioamin",15)) caseclassMatch(Empolyee("wuye")) caseclassMatch(Empolyee("penglong")) } } class Person case class CTO(name:String,floor: Int) extends Person case class Empolyee(name:String) extends Person case class Other(name:String) extends Person