快學scala之Array、List、tuple模式匹配
阿新 • • 發佈:2019-01-02
object operate_match { def main(args: Array[String]) { // map match val map = Map("scala" -> "spark", "java" -> "hadoop") map match { case m: Map[_, _] => println("--------------") case _ => println("nothing") } //arr match val arr = Array(0, 2, 3, 4) arrmatch { case Array(0) => println(0) //match array which has one element case Array(x, y) => println(x + y) //match which has two element case Array(0, _*) => println("0......") //match first element is 0 case _ => println("something ") // default } //match List val list = "apple" :: "pear" ::"mango" :: Nil list match { case "" :: Nil => "sale out" case x :: y => x + " " + y case _ => "no fruit" } //match tuple val tuple = ("taobao", "baidu", "QQ", "google") tuple match { case ("", _, _, _) => "0......" case (x, _, y, _) => x + " " //元組不支援_*匹配 case _ => " no such company"} /* 提取器背後是extractor機制,帶有從物件中提取值的unapply或unapplySeq方法 unapply提取的是一個序列 */ //變數中的模式 val (x, y) = (1, 2) // x = 1 , y = 2 val (q, r) = BigInt(10) /% 3 // /*表示商和餘數的對偶 q:商 r:餘數 val Array(first, second, _*) = arr // first second 為第一,第二個 //獲取系統配置 import scala.collection.JavaConversions.propertiesAsScalaMap for ((k, v) <- System.getProperties()) println(k + "\t" + v) val litchi = Litchi("Litchi", 8.0) litchi match { // case Apple(v) => "name : " + v case Litchi(n, p) => "name : " + n + "\t price : " + p // case Nothing => "no fruit" } } //Option型別:表示可能存在,也可能不存在的型別(要麼為空,要麼帶單個元素) //Some("")表示包含某個值 //Map.get返回Option如果對於給定的鍵沒有對應的值返回None,如果有值返回Some //偏函式:類PartialFunction[A,B](A是引數型別,B返回型別) //有兩個方法apply:從匹配的模式計算函式值,isDefineAt對輸入匹配一個模式是返回true val f: PartialFunction[Char, Int] = { case '+' => 1 case '-' => -1 } f.isDefinedAt('0') // 返回false f('+') //返回 1 // f('0') //丟擲MatchError }