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) arr match { 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 }
快學scala之Array、List、tuple模式匹配
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.