scala--match模式匹配
scala中模式匹配,类似于Java中的swich case语法,即对一个值进行条件判断,然后针对不同的条件,进行不同的处理。
但是Scala的模式匹配的功能比Java的swich case的功能要强大地多,Java的swich case语法只能对值进行匹配。但是Scala的模式匹配除了可以对值进行匹配之外,还可以对类型进行匹配、对Array和List的元素情况进行匹配、对case class进行匹配、甚至对有值或没值(Option)进行匹配。
1、基础语法--对变量的匹配:(案例:成绩评价)
match case的语法如下:变量 match { case 值 => 代码 }。如果值为下划线,则代表了不满足以上所有情况下的默认情况如何处理。此外,match case中,只要一个case分支满足并处理了,就不会继续判断下一个case分支了,在每个case语句最后,不需要break,break是隐含的
案例:
def judgeGrade(grade: String) {
grade match {
case "A" => println("Excellent")
case "B" => println("Good")
case _ => println("you need work harder")
}
}
Scala的模式匹配语法,有一个特点在于,可以在case后的条件判断中,不仅仅只是提供一个值,而是可以在值后面再加一个if守卫,进行双重过滤
此案例是如果不满足"A","B",再进行if判断,因为模式匹配是从上往下进行的
案例:
def judgeGrade(name: String, grade: String) {
grade match {
case "A" => println(name + ", you are excellent")
case "B" => println(name + ", you are good")
case _ if name == "leo" => println(name + ", you are a good boy, come on")
case _ => println("you need to work harder")
}
}
Scala的模式匹配语法,有一个特点在于,可以将模式匹配的默认情况,下划线,替换为一个变量名,此时模式匹配语法就会将要匹配的值赋值给这个变量,从而可以在后面的处理语句中使用要匹配的值
案例:
def judgeGrade(name: String, grade: String) {
grade match {
case "A" => println(name + ", you are excellent")
case "B" => println(name + ", you are good")
case grade if name == "leo" => println(name + ", you are a good boy, come on, your grade is " + grade)
case grade => println(name + ", you should study, your grade is " + grade)
}
}
2、对类型进行模式匹配(案例:异常处理)
match可以直接匹配类型,这点是java的switch case绝对做不到的。
案例:
import java.io._
def processException(e: Exception) {
e match {
case e1: IllegalArgumentException => println("you have illegal arguments! exception is: " + e1)
case e2: IOException => println("you got an IOError! exception is: " + e3)
case _: Exception => println("cannot know which exception you have!" )
}
}
3、对Array和List的元素进行模式匹配(案例:对朋友打招呼)
对Array进行模式匹配,分别可以匹配带有指定元素的数组、带有指定个数元素的数组、以某元素打头的数组
四种情况匹配下面四种结果:greeting("Leo") , greeting("marry","lucy","rise"), greeting("Leo","tom"), greeting("jack")
案例:
def greeting(arr: Array[String]) {
arr match {
case Array("Leo") => println("Hi, Leo!") -->greeting("Leo")
case Array(girl1, girl2, girl3) => println("Hi, girls, nice to meet you. " + girl1 + " and " + girl2 + " and " + girl3) -->greeting("marry","lucy","rise")
case Array("Leo", _*) => println("Hi, Leo, please introduce your friends to me.") -- >greeting("Leo","tom")
case _ => println("hey, who are you?") -->greeting("jack")
}
}
对List进行模式匹配,与Array类似,但是需要使用List特有的::操作符,这个操作符的含义就是连接list的元素,连接Nil就是空,说明后面没有值。tail表示以"Leo"
开头,后面的都是"尾"
案例:
def greeting(list: List[String]) {
list match {
case "Leo" :: Nil => println("Hi, Leo!")
case girl1 :: girl2 :: girl3 :: Nil => println("Hi, girls, nice to meet you. " + girl1 + " and " + girl2 + " and " + girl3)
case "Leo" :: tail => println("Hi, Leo, please introduce your friends to me.")
case _ => println("hey, who are you?")
}
}
4、case class与模式匹配(案例:学校门禁)
Scala中提供了一种特殊的类,用case class进行声明,也可以称作样例类。它类似于Java中的JavaBean的概念。即只定义field,并且由Scala编译时自动提供getter和setter方法,但是没有method。
case class的主构造函数接收的参数通常不需要使用var或val修饰,Scala默认val修饰。自己也可以用var定义。同时Scala自动为case class定义了伴生对象,也就是object,并且定义了apply()方法,该方法接收主构造函数中相同的参数,并返回case class对象
案例:
class Person
case class Teacher(name: String, subject: String) extends Person
case class Student(name: String, classroom: String) extends Person
def judgeIdentify(p: Person) {
p match {
case Teacher(name, subject) => println("Teacher, name is " + name + ", subject is " + subject)
case Student(name, classroom) => println("Student, name is " + name + ", classroom is " + classroom)
case _ => println("Illegal access, please go out of the school!")
}
}
当传入老师可学生的对象的时候是可以匹配到相应情况的,但假如你定义了Worker类继承Person,就是最后一种情况了
只要在声明类时 在class关键字前加上case关键字 这个类就成为了样例类
样例类和普通的区别在于:
(1)默认实现序列化接口
(2)默认自动覆盖 toString equals hashCode方法
(3)不需要new可以直接生成对象
(4)支持模式匹配
object TermTest extends scala.App {
def printTerm(term: Term) {
term match {
case Var(n) =>
print(n)
case Fun(x, b) =>
print("^" + x + ".")
printTerm(b)
case App(f, v) =>
print("(")
printTerm(f)
print(" ")
printTerm(v)
print(")")
}
}
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
val id = Fun("x", Var("x"))
val t = Fun("x", Fun("y", App(Var("x"), Var("y"))))
printTerm(t)
println
println(isIdentityFun(id))
println(isIdentityFun(t))
}
5、Option与模式匹配(案例:成绩查询)
Option有两种值,一种是Some,表示有值,一种是None,表示没有值。它用于判断某个变量是有值还是没有值
比如如果按照学号查找学生有成绩就输出成绩(grade有值),如果没有grade值,就代表None
案例:
val grades = Map("Leo" -> "A", "Jack" -> "B", "Jen" -> "C")
def getGrade(name: String) {
val grade = grades.get(name)
grade match {
case Some(grade) => println("your grade is " + grade)
case None => println("Sorry, your grade information is not in the system")
}
}
上一篇: AndroidStudio常见问题解决
下一篇: java基础第十九篇之Xml