scala中的模式匹配
基本语法
1 变量 match { 2 case 值1 => 代码 3 case 值2 => 代码 4 ... 5 case 值N if (...) => 代码 6 case _ => 代码 7 }
常量匹配
1 scala> def matchConstant(x:Any) = x match { 2 | case 1 => "One" 3 | case "two" => "Two" 4 | case "3" => "Three" 5 | case true => "True" 6 | case null => "null value" 7 | case Nil => "empty list" 8 | case _ => "other value" 9 | }
特别需要注意的是,Nil是一个空的List,定义为List[Nothing]。
变量匹配
1 scala> def matchVariable(x:Any) = x match { 2 | case x if(x==1) => x 3 | case x if(x=="Tony") => x 4 | case x:String => "other value:" + x 5 | case _ => "unexpected value:"+x 6 | }
类型匹配
1 scala> def matchType(x:Any) = x match { 2 | case s:String => "the string length is:"+s.length 3 | case m:Map[_,_] => "the map size is:"+m.size 4 | case _:Int | _:Double => "the number is:"+x 5 | case _ => "unexpected value:"+x 6 | }
case class匹配
1 class DataFrameWork 2 case class ComputationFramework(name: String, pupular:Boolean) extends DataFrameWork 3 case class StorageFramework(name:String, popular:Boolean) extends DataFrameWork 4 5 def getBigDataType(data: DataFrameWork){ 6 data match { 7 case ComputationFramework(name, popular) => println("[ComputationFramework]name: " + name + " and popular: " + popular) 8 case StorageFramework(name, popular) => println("[StorageFramework]name: " + name + " and popular: " + popular) 9 case _ => println("Other situation") 10 } 11 }
option匹配
Scala有一种特殊的类型Option,Option有两种值,一种是Some,表示有值,一种是None,表示没有值。Option通常会用于模式匹配中,用于判断某个变量是有值还是没有值,这比null来的更加简洁明了。
1 def getValue(key:String, content:Map[String, String]){ 2 content.get(key) match { 3 case Some(value) => println(value) 4 case None => println("NOT FIND") 5 } 6 }
数组匹配
1 def getMatchCollection(msg : Array[String]) { 2 msg match { 3 case Array("Scala") => println("One Element") 4 case Array("Scala", "Java") => println("Two Element") 5 case Array("Spark", _*) => println("Some Element begin with Spark") 6 case _ => println("Unknown type") 7 } 8 }
元组匹配
1 def tupleMatch(t : Tuple2[String, String]) : String = t match { 2 case ("A", _) => "匹配以A开始的二元组" 3 case (_, "A") => "匹配以A结束的二元组" 4 case _ => "其他情况" 5 }
List匹配
def listMatch(list : List[String]) = list match { case head :: Nil => "匹配只有一个元素的情况" case x :: y :: Nil => "匹配只有两个元素的情况" case "丽丽" :: tail => "匹配以丽丽开始的情况" case head :: tail => "匹配多个元素的情况" case _ => "其他情况" }
list分为head和tail两个部分,head是list的第一个元素,tail是list中除了head外的其余元素组成的list。用::连接list时,尾节点要声明成Nil。
变量绑定
可以将匹配的对象绑定到变量上。首先写一个变量名,然后写一个@符号,最后写入该匹配的对象。如果匹配成功,则将变量设置为匹配的对象。
1 scala> case class Person(name: String, age: Int) 2 defined class Person 3 4 scala> val person = Person("Tony",18) 5 person: Person = Person(Tony,18) 6 7 scala> person match { 8 | case p @Person(_,age) => println(s"${p.name},age is $age") 9 | case _ => println("Not a person") 10 | } 11 Tony,age is 18
参考:
https://www.jianshu.com/p/d07e0bcfea3a
https://www.jianshu.com/p/1456f065a4bb