本文作者:林伟兵,叩丁狼高级讲师。原创文章,转载请注明出处。
在Java中我们可以通过switch..case语句来实现模式匹配,在scala中提供了match case实现模式匹配。
普通的模式匹配语句如下:
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)
除了满足普通的匹配,还可以进行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")
}
}
也可以对类型进行匹配:
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("李四"))
对于map取值来说,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("找不到....")
}
想获取更多技术视频,请前往叩丁狼官网:http://www.wolfcode.cn/openClassWeb_listDetail.html
网友评论