除了普通的×××、字符串类型的模式匹配,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))
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。