目录
介绍
类似Java中的switch case
变量 match{
case value1 => xxx
case value2 => xxx
.....
case _ => xxx
}
1)基本匹配
val names = Array("lisi", "zhangsan", "wanger")
val name = names(Random.nextInt(names.length))
name match {
case "lisi" => println("MR li")
case "zhangsan" => println("MR zhang")
case _ => println("who?")
}
// 结果
MR li
2)含有条件的匹配
def judgeScore(name: String, score: String): Unit = {
score match {
case "A" => println("very good.")
case "B" => println("not bad")
case "C" => println("need work.")
case _ if (name == "lisi") => println(name + ", you could better")
case _ => println("hehe.....")
}
}
judgeScore("zhangsan", "E")
judgeScore("lisi", "A")
// 结果
hehe.....
very good.
3)Array 匹配
我们公司用到较多的
// Array
def greeting(array: Array[String]): Unit = {
array match {
case Array("zhangsan") => println("hi, zhangsan")
case Array(x, y) => println("hi, " + x + ", " + y)
case Array("zhangsan", _*) => println("hi, zhangsan and others")
case _ => println("hi, everyone....")
}
}
greeting(Array("zhangsan"))
greeting(Array("lisi", "wanger"))
greeting(Array("zhangsan", "lisi", "zhaosi"))
greeting(Array("lisi", "zhangsan", "wanger"))
// 结果
hi, zhangsan
hi, lisi, wanger
hi, zhangsan and others
hi, everyone....
4)List匹配
// List
def greeting(list: List[String]): Unit = {
list match {
case "zhangsan" :: Nil => println("zhangsan")
case x :: y :: Nil => println(x + ", " + y)
case _ => println("hi, everyone")
}
}
greeting(List("zhangsan"))
greeting(List("zhangsan", "li"))
greeting(List("wanger", "zhangsan", "lisi"))
// 结果
zhangsan
zhangsan, li
hi, everyone
5)数据类型匹配
// 类型匹配
def matchType(obj: Any): Unit = {
obj match {
case x: Int => println("Int")
case s: String => println("string")
case m: Map[_, _] => m.foreach(println)
case _ => println("other type")
}
}
matchType(1)
matchType("lisi")
matchType(1l)
matchType(Map("name" -> "lisi"))
// 结果
Int
string
other type
(name,lisi)
6)异常处理
// 异常处理
try {
val i = 10 / 0
println(i)
} catch {
case e: ArithmeticException => println("除数不能是0")
case e: Exception => println(e.getMessage)
} finally {
}
// 结果
除数不能是0
7)case class匹配
// case class
class Person
case class CTO(name: String, floor: String) extends Person
case class Employee(name: String, floor: String) extends Person
case class Other(name: String) extends Person
def caseclassMatche(person: Person): Unit = {
person match {
case CTO(name, floor) => println("CTO NAME IS: " + name + ", floor is: " + floor)
case Employee(name, floor) => println("EMPLOYEE NAME IS: " + name + ", floor is: " + floor)
case _ => println("other")
}
}
caseclassMatche(CTO("lisi", "10"))
caseclassMatche(Employee("zhangsan", "3"))
caseclassMatche(Other("wanger"))
// 结果
CTO NAME IS: lisi, floor is: 10
EMPLOYEE NAME IS: zhangsan, florr is: 3
other