1. 程式人生 > >scala模式匹配+案例教學

scala模式匹配+案例教學

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,就是最後一種情況了

 

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")

  }

}