match case 高阶匹配
(一)
- 匹配元组不同的元素的数量
- 匹配数组特殊值
- 匹配类型的类型
格式:
def processValue(value: Any): Unit =
value match {
case i: Int => println(s"这是一个整数:$i")
case d: Double => println(s"这是一个双精度浮点数:$d")
case s: String => println(s"这是一个字符串:$s")
case b: Boolean => println(s"这是一个布尔值:$b")
case _ => println("这是其他类型")
}
}
matchType(5)
matchType("Hello")
代码示例:
object case01 {
def matchType(value:Any):Unit = {
value match {
case x:Int => println(s"${x} 是Int")
case x:Double => println(s"${x} 是Double")
case _ => println("未知")
}
}
def main(args: Array[String]): Unit = {
matchType(1)
matchType(1.1)
}
}
(二)
- 匹配元组不同的元素的数量
- 匹配数组特殊值
- 匹配变量的类型
- 匹配样例类(属性值)
object case02 {
case class Circle(radius: Double) {}
case class Rectangle(width: Double, height: Double) {}
def getArea(shape: Any): Double = {
shape match {
case Circle(radius) => math.Pi * radius * radius
case Rectangle(width, height) => width * height
case _ => 0.0
}
}
def main(args: Array[String]): Unit = {
val circle = Circle(2.0)
val rectangle = Rectangle(2.0, 3.0)
println(getArea(circle))
println(getArea(rectangle))
}
}
高阶匹配之匹配案例类
object case03 {
def main(args: Array[String]): Unit = {
val m1 = Map(
"马云 - 阿里巴巴" -> 1964,
"张一鸣 - 字节跳动" -> 1983,
"刘强东 - 京东" -> 1974,
"程维 - 滴滴" -> 1983
)
for((key,1983) <- m1){
println(key)
}
for((key,value) <- m1){
if(value == 1983)
println(key)
}
}
}
object case04 {
def main(args: Array[String]): Unit = {
val arr = Array(1, 22, 33, 4, 5, 6)
val Array(x, y, z, _*) = arr
println("x=" + x + ",y=" + y + ",z=" + z)
}
}