scala 常用模式匹配類型
阿新 • • 發佈:2019-01-16
tor 結果 sparksql 伴生對象 結構 any bsp case 使用方法
模式匹配的類型
包括:
- 常量模式
- 變量模式
- 構造器模式
- 序列模式
- 元組模式
- 變量綁定模式等。
常量模式匹配
常量模式匹配,就是在模式匹配中匹配常量
objectConstantPattern{ def main(args:Array[String]) :Unit = { //模式匹配結果作為函數返回值 defpatternShow(x : Any) = x match { case 5 => "五" case true => "真" case "test" => "字符串" casenull => "null值" case Nil => "空列表" case _ => "其他常量" } println(patternShow(5)) println(patternShow(true)) println(patternShow(List())) } }
變量匹配
變量匹配,匹的是case語句後面接的是scala變量,如case x if(x == 5) => x等,在使用時一般會加守衛條件,當然也可以像case x => x這樣使用,它會匹配任何輸入的合法變量。
objectVariablePattern{ def main(args:Array[String]) :Unit = { //模式匹配結果作為函數返回值 defpatternShow(x : Any) = x match { case x if (x == 5) => x case x if (x == "Scala") => x case _ => } println(patternShow(5)) println(patternShow("Scala")) } }
構造器模式
構造器模式指的是,直接在case語句後面接類構造器,匹配的內容放置在構造器參數中。
//將Person類定義為case class case class Person(name : String,age : Int) object ConstructorPattern{ def main(args:Array[String]) :Unit = { val p = new Person("nyz",27) def constructorPattern(p : Person) = p match { //構造器模式必須將Person類定義為case class,否則需要自己定義伴生對象並實現unapply方法。 case Person(name,age) => "name =" + name + ",age =" + age //case Person(_,age) => "age =" + age case _ => "Other" } println(constructorPattern(p)) } }
序列化模式
序列模式用於匹配如數組Array、列表List、Range這樣的線性結構集合,其實原理也是通過case class起作用的。
object SequencePattern{ def main(args:Array[String]) :Unit = { val list = List("spark","Hive","SparkSQL") val arr = Array("SparkR","Spark Streaming","Spark MLib") def sequencePattern(p : Any) = p match {{ //序列模式匹配,_*表示匹配剩余內容,first、second匹配數組p中的第一、二個元素 case Array(first,second,_*) => first + "," + second //_匹配數組p的第一個元素,但不賦給任何變量 case List(_,second,_*) => second case _ => "Other" } println(SequencePattern(list)) println(SequencePattern(arr)) } }
元組模式
元組模式用於匹配scala中的元組內容,用於匹配元組類型的變量內容
object TuplePattern{ def main(args:Array[String]) :Unit = { val list = List("spark","Hive","SparkSQL") def tuplePattern(t : Any) = t match {{ case (one,_,_) => one //_*不適合用於元組,只適用於序列 //case (one,_*) => one case _ => "Other" } println(tuplePattern(t)) } }
類型模式
它可以匹配輸入待匹配變量的類型
object TypePattern{ def main(args:Array[String]) :Unit = { def typePattern(t : Any) = t match { case t : String => "String" case t : Int => "Intger" case t : Double => "Double" case _ => "Other Type" } }
變量綁定模式
在進行模式匹配時,有時不僅僅只是返回一個變量,也可以將某個變量綁定到某個模式上。從而將整體匹配結果賦值給該變量。
具體使用方法是在模式前面加變量和@符號。
object VariableBindingPattern{ def main(args:Array[String]) :Unit = { var t = List(List(1,2,3),List(2,3,4)) def variableBindingPattern(t : Any) = t match {{ //變量綁定,采用變量名(這裏是e) //與@符號,如果後面的模式匹配成功,則將整體匹配結果作為返回值 case List(_,e@List(_,_,_)) => e case _ => Nil } println(variableBindingPattern(t)) } }
scala 常用模式匹配類型