match case的基本格式
package matchcase
*
object matchcase01 {
def main(args: Array[String]): Unit = {
println(getProvinceName(11))
println(getProvinceName(12))
println(getProvinceName(13))
}
def getProvinceName(code:Int):String= {
code match {
case 11 => "北京"
case 12 => "天津"
case 13 => "河北"
case _ => "未知"
}
}
}
package matchcase
*
object matchcase02 {
def main(args: Array[String]): Unit = {
val xiaohong = (100, 100, 100)
val xiaoming = (89, 98)
getScore(xiaohong)
getScore(xiaoming)
getScore((1, 2, 3, 4))
}
def getScore(score: (Int, Int, Int)): Unit = {
score match {
case (a, b, c) => println("元组中有三个元素:a = " + a + "b = " + b + ",c = " + c)
case (a, b) => println("元组中有两个元素:a = " + a + "b = " + b)
case _ => println("未知")
}
}
}
(三)高阶匹配之元组元素数量
package matchcase
*
object matchcase03 {
def main(args: Array[String]): Unit = {
testType(1)
testType(1.1)
testType("1")
}
def testType(i:Any):Unit= {
i match {
case x: Int => println("当前变量是:Int")
case x: Double => println("当前变量是:Double")
case _ => println("未知")
}
}
}
( 四)高阶匹配之匹配元素特征
package matchcase
*
object matchcase04 {
def main(args: Array[String]): Unit = {
testType(Array(1,2,3))
testType(Array(1,2,3,4))
testType(Array(11,2,3,4))
testType(Array(11,1,3,4))
}
def testType(i:Any):Unit= {
arr match {
case Array(1,x,y) => println("arr是一个数组,有三个元素,第一个1")
case Array(1,x,y,z) => println("arr是一个数组,有四个元素,第一个1")
case Array(x,1,y,z) => println("arr是一个数组,有四个元素,第二个11")
case _ => println("未知")
}
}
}
(五)高阶匹配之变量类型匹配
package matchcase
object matchcase05 {
case class Circle(radius: Double)
case class Rectangle(width: Double, height: Double)
def getArea(obj: Any): Unit = {
obj match {
case Circle(radius) => println("圆的面积是:" + radius * radius * 3.14)
case Rectangle(width, height) => println("矩形的面积是:" + width * height)
case _ => println("未知")
}
}
def main(args: Array[String]): Unit = {
getArea(Circle(2))
getArea(Rectangle(2, 3))
getArea("abc")
}
}
package matchcase
object matchcase06 {
def main(args: Array[String]): Unit = {
val arr =Array(1,2,3,4)
var a = arr(0)
var b = arr(1)
var c = arr(2)
println("a = " + a + "b = " + b + "c = " + c)
val Array(x,y,z,_*) = arr
println("x = " + x + "y = " + y + "z = " + z)
}
}
package matchcase
object matchcase07 {
def main(args: Array[String]): Unit = {
val a = 11
a match {
case x:Int if a > 10 => println("a 是大于10的Int")
case _ => println("a is not Int")
}
}
}