本文作者:林偉兵,叩丁狼高級(jí)講師。原創(chuàng)文章殉了,轉(zhuǎn)載請(qǐng)注明出處。
在Java中我們可以通過(guò)switch..case語(yǔ)句來(lái)實(shí)現(xiàn)模式匹配拟枚,在scala中提供了match case實(shí)現(xiàn)模式匹配薪铜。
普通的模式匹配語(yǔ)句如下:
val arr = Array("spark","storm","flink","hadoop")
val name = arr(scala.util.Random.nextInt(arr.length))
val tipStr = name match {
case "spark" => "This is a spark book "
case "storm" => "This is a storm book "
case "flink" => "This is a flink book "
case "hadoop" => "This is a hadoop book "
case _ => "i don't know !"
}
println(tipStr)
除了滿足普通的匹配,還可以進(jìn)行Array匹配,如下代碼:
sayHi("",Array("Zhangsan"))
sayHi("lisi",Array("lisi"))
def sayHi(name:String, arr: Array[String]): Unit ={
arr match {
case Array("Zhangsan") => println("Hi , zhangsan...")
case Array(x,y) => println("Hi,"+x + ","+ y)
case Array("Zhangsan",_*) => println("Hi,Zhangsan and others...")
case _ if name == "lisi" => println("lisi jun")
case _ => println("Hi everyones")
}
}
將上面的匹配換成List,如下代碼:
sayHi(List("Zhangsan"))
sayHi(List("lisi","wangwu"))
sayHi(List("Zhangsan","lisi","wangwu"))
sayHi(List("wangwu"))
def sayHi(arr: List[String]): Unit ={
arr match {
case "Zhangsan" :: Nil => println("Hi , zhangsan...")
case x :: y :: Nil => println("Hi,"+x + ","+ y)
case "Zhangsan":: tail => println("Hi,Zhangsan and others...")
case _ => println("Hi everyones")
}
}
也可以對(duì)類型進(jìn)行匹配:
checkType(33)
checkType("Hello world")
checkType(15.9f)
def checkType(obj:Any): Unit ={
obj match {
case x:Int => println("pass type is Int")
case x:Double => println("pass type is Double")
case x:String => println("pass type is String")
case _ => println("pass type is Others...")
}
}
捕獲多種異常的處理:
try{
val arr = Array()
print("arr(11) :"+ arr(11))
}catch {
case e:ArrayIndexOutOfBoundsException => println("ArrayIndexOutOfBoundsException:"+e.getLocalizedMessage)
case e:Exception => println("Exception:"+e)
}
模式匹配還支持泛型操作:
class Person(name:String)
case class Teacher(name:String, grade:Int) extends Person(name)
case class Student(name:String, age:Int) extends Person(name)
case class OtherPerson(name:String) extends Person(name)
def doWork(person:Person): Unit ={
person match {
case Teacher(name, grade) => println(s"teacher grade")
case Student(name, age) => println(s"student age")
case _ => println(s"other person is working...")
}
}
doWork(new Student("張三",22))
doWork(new Teacher("李四", 5))
doWork(new OtherPerson("李四"))
對(duì)于map取值來(lái)說(shuō)恩溅,Some和None模式匹配:
val map = Map("php" -> 85, "bigdata" -> 99)
val item = map.get("php")
item match {
case Some(x) => println("item 是"+ x)
case None => println("找不到....")
}
想獲取更多技術(shù)視頻隔箍,請(qǐng)前往叩丁狼官網(wǎng):http://www.wolfcode.cn/openClassWeb_listDetail.html