scala的模式匹配类似于 java 的 switch case ,然而又有所不同。scala中不仅可以匹配变量的值,还可以匹配类型。
scala的模式匹配中没有break语句,一旦发现匹配成功就立刻返回,不会有java中case穿透的问题。
但是scala的模式匹配最好写上类似java switch case中的default,否则所有分支都不能匹配的情况下会报错。这点也是跟java的switch case不同的地方。
import java.io._
object TestSwitch {
def main(args: Array[String]): Unit = {
//简单示例
def judgeGrade(grade :String,name :String=""): Unit ={
grade match {
case "A" => println("Excellent!")
case "B" => println("Good!")
case "C" => println("Just so so.")
case grade if name == "leo" => println("You're a good boy,don't be sad.")
// case _ => println("You need to work harder." + _) //不能用下划线的方式调用,需要给出变量名。如果不需要调用传入的值,直接写case _ => {函数体} 即可
case grade => println(s"""${name},You got an "${grade}" ,please work harder.""")
}
}
//匹配对象
def catchException(e :Exception){
e match {
case e1: IllegalArgumentException => println(e1 + ": Wrong args!")
case e2: IOException => println(e2 + " occurs!")
case e3: FileNotFoundException => println(e3 + ": No such file!")
case e4: Exception => println("Unknown exception occurs!")
}
}
//直接匹配一个数组
def greeting(args : Array[String]): Unit ={
args match {
case Array("cat") => println("hi, kitten~")
case Array("dog1","dog2","dog3") => println("hi,puppy~")
case Array("rabbit",_*) => println("rabbit and her friends~") //_* 表示后面有多个元素,这个分支匹配第一个元素是"rabbit"的数组。
case _ => println("I don't known who they are.")
}
}
//scala的Option类型只有两个值:Some()和 None,表示有值和没有值。调用grades.get()返回的就是Option类型。
val grades = Map("Jack" -> "A","Lily" -> "B","Tom" -> "C")
def getGrade(name :String): Unit ={
val grade = grades.get(name)
grade match {
case Some(grade) => println(grade)
case None => println("No information.")
}
}
judgeGrade("D","Lily")
catchException(new IOException())
greeting(Array("shark"))
getGrade("Jack")
}
}
//匹配样例类
//定义样例类
//样例类类似于JavaBean,只有field,没有除get和set以外的method。定义了一个case class ,系统会自动为它生成get和set方法。
//这个例子想要实现门禁的功能,只允许老师和学生进入学校,闲人勿近。
scala> class Person2
defined class Person2
scala> case class Teacher(name :String) extends Person2
defined class Teacher
scala> case class Student(name :String) extends Person2
defined class Student
scala> case class Worker(name :String) extends Person2
defined class Worker
//实现门禁方法
scala> def AccessControl(p :Person2){
p match {
case Teacher(name) => println(s"hi,${name}.Please come in.")
case Student(name) => println(s"morning ${name},hurry up,don't be late.")
case _ => println("Illegal access.")
}
}
AccessControl: (p: Person2)Unit
//除了自动生成get和set方法,系统还会自动为case class生成伴生对象并实现apply方法。所以我们可以直接写Teacher("Teacher Liu"),不用写new关键字。
//来了一位老师
scala> val t = Teacher("Teacher Liu")
t: Teacher = Teacher(Teacher Liu)
//来了一名学生
scala> val s = Student("lisa")
s: Student = Student(lisa)
//来了一位家长同志,是一名苦逼码农。
scala> val w = Worker("Mr Zhou")
w: Worker = Worker(Mr Zhou)
//老师可以进入
scala> AccessControl(t)
hi,Teacher Liu.Please come in.
//学生可以进入
scala> AccessControl(s)
morning lisa,hurry up,don't be late.
//闲人勿近
scala> AccessControl(w)
Illegal access.