高阶匹配之匹配元素特征
模式匹配还可以根据数组元素的个数,元素的特征来匹配。
package matchcase
object Case04 {
/*
match case的应用场景
1. 匹配不同的类型的数量
2. 匹配通用的类型
3. 匹配变量的类型
*/
val a: Int = 1
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 Case05 {
// match case 高阶匹配
// 1. 匹配元组的不同元素的数量
// 2. 匹配特定的值
// 3. 匹配变量的类型
// 4. 匹配样例类(属性值)
// 1. 圆形类
case class Circle(radius: Double) {}
// 2. 矩形类
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 = {
// 1. 实例化圆形对象
val circle = Circle(2.0)
// 2. 实例化矩形对象
val rectangle = Rectangle(2.0, 3.0)
println(getArea(circle))
println(getArea(rectangle))
}
}
匹配for表达式
从Map中打印所有年龄为1971的创业者的信息。
package matchcase
object Case06 {
val m1 = Map(
"马云 - 阿里巴巴" -> 1964,
"张一鸣 - 字节跳动" -> 1983,
"刘强东 - 京东" -> 1974,
"程维 - 滴滴" -> 1983
)
// 找出所有1983年出生的企业家(方式1:模式匹配)
for ((key, 1983) <- m1) {
println(key)
}
// 找出所有1983年出生的企业家(方式2:条件判断)
for ((key, value) <- m1) {
if (value == 1983)
println(key)
}
}
练习
package matchcase
object Case07 {
def main(args: Array[String]): Unit = {
// 定义一个数组,包含4个元素(其中第4个元素是子数组)
val arr = Array(11, 22, 33, Array(4, 5, 6))
// 原始方式:通过索引获取前3个元素
var x = arr(0)
var y = arr(1)
var z = arr(2)
println("x=" + x + ", y=" + y + ", z=" + z)
// 优化方式:使用数组模式匹配提取前3个元素
val Array(x1, y1, z1, _*) = arr
println("x=" + x1 + ", y=" + y1 + ", z=" + z1)
}
}