Scala入門7之模式匹配
阿新 • • 發佈:2020-12-29
模式匹配
\quad \quad Scala 提供了強大的模式匹配機制,應用也非常廣泛。可以應用在很多場景:
- switch語句
- 型別查詢
- 使用模式匹配快速獲取資料
- 一個模式匹配包含了一系列備選項,每個都開始於關鍵字 case。每個備選項都包含了一個模式及一到多個表示式。箭頭符號 => 隔開了模式和表示式。
1、簡單模式匹配
\quad \quad 在Java中,有switch關鍵字,可以簡化if條件判斷語句。在scala中,可以使用match表示式替代。
語法
變數名 match {
case "常量1" => 表示式1
case "常量2" => 表示式2
......
case _ => 表示式 // _表示其他情況
例子:
// 匯入Random包
import scala.util.Random
object MatchApp {
def main(args: Array[String]): Unit = {
val random = new Random()
val names = Array("Akiho Yoshizawa","YuiHatano" ,"Aoi Sola")
// 隨機選取一個名字
val name = names(random.nextInt(names.length))
name match{
case "Akiho Yoshizawa" => println("季老師..")
case "YuiHatano" => println("李老師..")
case _ => println("不知道")
}
}
}
2、型別模式匹配
\quad \quad 除了像Java中的switch匹配資料之外,match表示式還可以進行型別匹配。如果我們要根據不同的資料型別,來執行不同的邏輯,也可以使用match表示式來實現。
語法
變數名 match {
case 型別1變數名: 型別1 => 表示式1
case 型別2變數名: 型別2 => 表示式2
case 型別3變數名: 型別3 => 表示式3
......
case _ => 表示式4
}
- 型別即為scala的常見資料型別如Int,String
例子:
object Type extends App {
def matchType(obj:Any):Unit={
obj match {
case x:Int => println("Int")
case s:String => println("String")
case m:Map[_,_] => m.foreach(println)
case _ => println("other type")
}
}
matchType(1)
matchType("1")
matchType(Map("name"->"PK"))
}
結果:
3、集合模式匹配
3.1 Array模式匹配
語法
變數名 match{
case Array() => 表示式1
case Array() => 表示式2
......
case _ => 表示式 // _表示其他情況
- 其中,Array()中括號裡的內容隨便寫
object hello extends App {
def greeting(array:Array[String]):Unit={
array match{
case Array("zhangsan") => println("Hi:zhangsan")
case Array(x,y) => println("Hi:" + x +","+y)
case Array("zhangsan",_*) => println("Hi:zhangsan and other friends")// _*表示任意內容
case _ => println("Hi:everybody")
}
}
greeting(Array("zhangsan"))
}
3.2 List 模式匹配
語法
變數名 match{
case "常量1"::Nil => 表示式1
case "常量1"::"常量2"::Nil => 表示式2
case "常量1"::tail => 表示式3
......
case _ => 表示式
- Nil 表示空列表,tali表示任意
- _表示其他情況
object hello extends App {
def greeting(list:List[String]):Unit={
list match {
case "zhangsan"::Nil => println("Hello:zhangsan")
case x::y::Nil => println("Hello:"+x+" , "+y)
case _ =>println("Hello:everybody")
}
}
greeting(List("zhangsan","lisi"))
}
3.3 Tuple 模式匹配
語法
變數名 match{
case ("常量1") => 表示式1
case ("常量1","常量2") => 表示式2
......
case _ => 表示式3
4、case class 模式匹配
例子:
object Type extends App {
def caseclassMatch(person:Person):Unit={
person match {
case CTO(name,floor) => println("CTO name is:" +name +", floor is :" + floor)
case Employee(name,floor)=> println("Employee name is:" +name +", floor is :" + floor)
case _ => println("other")
}
}
class Person
case class CTO(name:String,floor:Int) extends Person
case class Employee(name:String,floor:Int) extends Person
case class Other(name:String,floor:Int) extends Person
caseclassMatch(CTO("pk",18))
caseclassMatch(Employee("zhangsan",20))
}