第27讲:Type、Array、List、Tuple模式匹配实战解析
除了普通的×××、字符串类型的模式匹配,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))
网页题目:第27讲:Type、Array、List、Tuple模式匹配实战解析
文章分享:http://www.jxjierui.cn/article/jhespo.html


咨询
建站咨询
