除了普通的×××、字符串类型的模式匹配,scala还提供了很多形式的模式匹配。例如Type、Array、List、Tuple

我们通过代码来说明。
类型模式匹配:判断传入值的类型
def match_type(t : Any) = t match {
case p : Int => println("It is a Integer!")
case p : String => println("It is a String! the content is :"+p)
case m : Map[_,_] => m.foreach(println)
case _ => println("Unknown Type")
}
match_type(1)
match_type("Spark")
match_type(Map("Spark"->"scala language"))运行结果如下
It is a Integer! It is a String! the content is :Spark (Spark,scala language)
特殊说明Map[_,_]中的两个_,表示任意类型。等同于type Map = Predef.Map[A, B] 但是不能写成Map[Any,Any]
数组模式匹配:
def match_array(arr : Any) = arr match {
case Array(x) => println("Array(1):",x) // 长度为1的数组,x代表数组中的值
case Array(x,y) => println("Array(2):",x,y) // 长度为2的数组,x代表数组中的第一个值
case Array(x,_*) => println("任意一维数组:",x) //任意长度数组,取第一个值
case Array(_*) => println("任意一维数组") //任意长度数组
}
match_array(Array(0))
match_array(Array("spark"))
match_array(Array("spark","scala"))
match_array(Array("spark","scala",0,4))列表匹配:
def match_list(lst : Any) = lst match {
case 0 :: Nil => println("List:"+0) //Nil表示空列表
case List(x) => println("List:"+x)
case x :: y :: Nil => println("List:"+x)
case x :: tail => println("List:"+"多元素List") //tail表示List的剩下所有元素
}
match_list(List(0))
match_list(List("spark"))
match_list(List("spark","hadoop"))
match_list(List("spark",1,2,4,5))元组匹配
def match_tuple(t : Any) = t match {
case (0,_) => println("二元元组,第一个值为0")
case (x,y) => println("二元元组,值为:"+x+","+y)
case _ => println("something else")
}
match_tuple((0,'x'))
match_tuple(('y','x'))
match_tuple((0,1,2,3))另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。