Scala中的模式匹配
模式匹配是Scala中非常有特色,非常强大的一种功能。模式匹配,其实类似于Java中的swich case语法,即对一个值进行条件判断,然后针对不同的条件,进行不同的处理。
但是Scala的模式匹配的功能比Java的swich case语法的功能要强大地多,Java的swich case语法只能对值进行匹配。但是Scala的模式匹配除了可以对值进行匹配之外,还可以对类型进行匹配、对Array和List的元素情况进行匹配、对case class进行匹配、甚至对有值或没值(Option)进行匹配。
而且对于Spark来说,Scala的模式匹配功能也是极其重要的,在spark源码中大量地使用了模式匹配功能。因此为了更好地编写Scala程序,并且更加通畅地看懂Spark的源码,学好模式匹配都是非常重要的。
1、模式匹配的基础语法(案例:成绩评价)
object test
{
def main
(args
: Array
[String]): Unit = {
def studentScore
(score
:String): Unit ={
score
match {
case "A"=>println
("excellent")
case "B"=>println
("good")
case "C"=>println
("soso")
case _
=>println
("you need work harder")
}
}
studentScore
("D")
}
}
在模式匹配中使用
if守卫
object test
{
def main
(args
: Array
[String]): Unit = {
def studentScore
(name
:String,score
:String): Unit ={
score
match {
case "A"=>println
("excellent")
case "B"=>println
("good")
case "C"=>println
("soso")
case _
if name
=="leo"=>print
(name
+",you are good boy,come on!")
case _
=>println
("you need work harder")
}
}
studentScore
("leo","D")
}
}
在模式匹配中进行变量赋值
object test
{
def main
(args
: Array
[String]): Unit = {
def studentScore
(name
:String,score
:String): Unit ={
score
match {
case "A"=>println
("excellent")
case "B"=>println
("good")
case "C"=>println
("soso")
case _
if name
=="leo"=>print
(name
+",you are good boy,come on!")
case _score
=>println
("you need work harder,your score only "+_score
)
}
}
studentScore
("le","F")
}
}
2、对类型进行模式匹配(案例:异常处理)
object test
{
def main
(args
: Array
[String]): Unit = {
import java
.io
._
def processException
(e
: Exception
) {
e
match {
case e1
: IllegalArgumentException
=> println
("you have illegal arguments! exception is: " + e1
)
case e2
: FileNotFoundException
=> println
("cannot find the file you need read or write!, exception is: " + e2
)
case e3
: IOException
=> println
("you got an error while you were doing IO operation! exception is: " + e3
)
case _
: Exception
=> println
("cannot know which exception you have!" )
}
}
processException
(new IOException
("not such file"))
}
}
3、对Array和List的元素进行模式匹配(案例:对朋友打招呼)
object test
{
def main
(args
: Array
[String]): Unit = {
def greeting
(arr
: Array
[String]) {
arr
match {
case Array
("Leo") => println
("Hi, Leo!")
case Array
(girl1
, girl2
, girl3
) => println
("Hi, girls, nice to meet you. " + girl1
+ " and " + girl2
+ " and " + girl3
)
case Array
("Leo", _
*) => println
("Hi, Leo, please introduce your friends to me.")
case _
=> println
("hey, who are you?")
}
}
greeting
(Array
("Leo","lily","poly","jack"))
}
}
object test
{
def main
(args
: Array
[String]): Unit = {
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?")
}
}
greeting
(List
("Leo","jack","poly","herry"))
}
}
4、case class与模式匹配(案例:学校门禁)
class Person
case class Teacher
(name
:String,subject
:String) extends Person
case class Student
(name
:String,classroom
:Int) extends Person
case class Worker
(name
:String,work
:String) extends Person
case class Stranger
() extends Person
object test
{
def main
(args
: Array
[String]): Unit = {
def entranceGuard
(p
:Person
): Unit ={
p
match {
case Student
(name
,classroom
)=>println
(s
"hello,$name,welcome to school,your classroom is $classroom")
case Teacher
(name
,subject
)=>println
(s
"hello,$name,welcome to school,your teach $subject")
case Worker
(name
,work
) if work
=="repairman"=>println
(s
"hello,$name,you should leave school afternoon")
case Worker
(name
,work
)=>println
(s
"hello,$name,you should leave school 2 hours later")
case _
=>println
(s
"stranger,you can not into school")
}
}
entranceGuard
(Worker
("Jason","cleaner"))
}
}
5、Option与模式匹配(案例:成绩查询)
object test
{
def main
(args
: Array
[String]): Unit = {
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")
}
}
getGrade
("J")
}
}