Scala 基礎(十四):Scala 模式匹配(二)

1 匹配數組

1)Array(0) 匹配只有一個元素且爲0的數組。數組

2)Array(x,y) 匹配數組有兩個元素,並將兩個元素賦值爲x和y。固然能夠依次類推Array(x,y,z) 匹配數組有3個元素的等等....app

3)Array(0,_*) 匹配數組以0開始spa

應用案例code

 

 2 匹配列表

應用案例對象

for (list <- Array(List(0), List(1, 0), List(0, 0, 0), List(1, 0, 0))) {
val result = list match {
case 0 :: Nil => "0" //
case x :: y :: Nil => x + " " + y //
case 0 :: tail => "0 ..." //
case _ => "something else"
}
println(result)
}

3 匹配元組

應用案例blog

// 元組匹配// 元組匹配
for (pair <- Array((0, 1), (1, 0), (1, 1),(1,0,2))) {
val result = pair match { // 
case (0, _) => "0 ..." //
case (y, 0) => y // 
case _ => "other" //.
}
println(result)
}

4 對象匹配

對象匹配,什麼纔算是匹配呢?,規則以下:three

1)case中對象的unapply方法(對象提取器)返回Some集合則爲匹配成功字符串

2)返回none集合則爲匹配失敗string

應用案例1it

object Square {
def unapply(z: Double): Option[Double] = Some(math.sqrt(z))
def apply(z: Double): Double = z * z
}
// 模式匹配使用:
val number: Double = 36.0
number match {
case Square(n) => println(n)
case _ => println("nothing matched")

應用案例1的小結

1)構建對象時apply會被調用 ,好比 val n1 = Square(5)

2)當將 Square(n) 寫在 case 後時[case Square(n) => xxx],會默認調用unapply 方法(對象提取器)

3)number 會被 傳遞給def unapply(z: Double) 的 z 形參

4)若是返回的是Some集合,則unapply提取器返回的結果會返回給 n 這個形參

5)case中對象的unapply方法(提取器)返回some集合則爲匹配成功

6)返回none集合則爲匹配失敗

應用案例2

object Names {
def unapplySeq(str: String): Option[Seq[String]] = {
if (str.contains(",")) Some(str.split(","))
else None
}}
val namesString = "Alice,Bob,Thomas"
//說明
namesString match {
case Names(first, second, third) => {
println("the string contains three people's names")
// 打印字符串
println(s"$first $second $third")
}
case _ => println("nothing matched")
}
相關文章
相關標籤/搜索