模式匹配
java : 对一个值进行条件判断,返回针对不同的条件进行不同的处理。
变量 match{
case value1=>代码1
case value2=>代码2
…
}
val names=Array("zhang","lisi","xiaoqiang")
val name=names(Random.nextInt(names.length))
name match {
case "zhang"=> print("季老师...")
case "lisi"=>print("李老师...")
case "xiaoqiang"=>print("陈老师")
case _ =>print("真不知道他们说什么")
}
def judge(grade:String):Unit={
grade match {
case "A"=>print("Excellent..")
case "B"=>print("good")
case _ => print("you need hard")
}
}
judge("D")
双层匹配
def judge(name:String,grade:String):Unit={
grade match {
case "A"=>print("Excellent..")
case "B"=>print("good")
case _ if(name=="lisi") => print(name+"you need hard")
}
}
judge("zhangsan","D")
//双层匹配。
judge("lisi","A")
数组匹配
列表匹配
类型匹配
异常处理
case class 匹配–针对对象
简单的来说,Scala的case class就是在普通的类定义前加case这个关键字,然后你可以对这些类来模式匹配。
case class带来的最大的好处是它们支持模式识别。
其次,如果我们想判断一个对象是否是某个类的对象,跟Java一样可以使用isInstanceOf
def caseclassMatch(student: Student):Unit={
student match {
case CTO(name,floor)=>print("cto name");
case Employee(name,floor)=>print("employee")
case _=>print("other")
}
}
class Student
case class CTO(name:String,floor:String) extends Student
case class Employee(name:String,floor:String) extends Student
case class Other(name:String,floor:String) extends Student
caseclassMatch(CTO("Pk","22"))
caseclassMatch(Employee("li","11"))
some&None模式匹配–针对map集合