scala 模式匹配之Type、Array、List和Tuple

时间:2021-09-29 21:43:58

1、代码

package com.yy.base

/**
* Scala 模式匹配
* Type Array List Tuple
*/
object PatternMatchMore extends App {

println("-----Type模式匹配------")
def typeMatch(t:Any) = t match{
case c:Int => println(c+"是个整数")
case c:String => println(c+"是个字符串")
case m:Map[_,_] => m.foreach(println)
case _ => println("没有匹配上")
}
//调用
typeMatch(2)
typeMatch("scala")
typeMatch(Map("name"->"yy"))

println("-----Array模式匹配------")
def arrayMatch(arr:Any) = arr match{
case Array(0) => println("Array是一个元素为0的数组")
case Array(x,y) => println("Array有两个元素:" + x +","+y)
case Array(0,_*) => println("Array至少有一个元素,且第一个元素为0")
case _ => println("其他类型的数组")
}
arrayMatch(Array(0))
arrayMatch(Array(0,1))
arrayMatch(Array(0,1,2,3,4,5))
arrayMatch(Array(1,2,3,4,5))

println("-----List模式匹配------")
def listMatch(list:Any) = list match{
case 0::Nil => println("List:0")
case x::y::Nil => println("List:" + x + "," + y)
case 0::tail => println("List:0......")
case _ => println("其他类型的List")
}
listMatch(List(0))
listMatch(List(1,2))
listMatch(List(0,1,2,3,4,5))
listMatch(List(1,2,3,4,5))

println("-----Tuple模式匹配------")
def tupleMatch(t:Any) = t match{
case (0,_) => println("Tuple start with 0")
case (x,0) => println("Tuple start with " + x)
case _ => println("其他类型的Tuple")
}
tupleMatch((0,"yy"))
tupleMatch(("xx",0))
tupleMatch((0,1,2,3))
}
2、结果

-----Type模式匹配------
2是个整数
scala是个字符串
(name,yy)
-----Array模式匹配------
Array是一个元素为0的数组
Array有两个元素:0,1
Array至少有一个元素,且第一个元素为0
其他类型的数组
-----List模式匹配------
List:0
List:1,2
List:0......
其他类型的List
-----Tuple模式匹配------
Tuple start with 0
Tuple start with xx
其他类型的Tuple