match case 匹配匹配
-
匹配元组不同的元素的数量
-
匹配数组特殊值
-
匹配变量的类型
object case04 {
/*
match case 匹配匹配
1. 匹配元组不同的元素的数量
2. 匹配数组特殊值
3. 匹配变量的类型
*/
var a:Int = 1;
/**
*
* @param value
*/
def matchType(value:Any):Unit = {
value match {
case x:Int => println(s"${x} is Int")
case x:Double => println(s"${x} is Double")
case _ => println("未知")
}
}
def main(args: Array[String]): Unit = {
matchType(1)
matchType(1.1)
}
}
match case 案例匹配
- 匹配样例类(属性值)
/*
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))
}
}
package matchcase
object case067 {
def main(args: Array[String]): Unit = {
// 定义一个数组,包含4个元素(其中第4个元素是子数组)
val arr = Array(11, 22, 33, Array(4,5,6))
// 方式1:通过数组索引提取前3个元素
// var x = arr(0)
//var y = arr(1)
//var z = arr(2)
//println("x=" + x + ", y=" + y + ", z=" + z)
// 方式2:使用match-case的数组模式匹配提取前3个元素
val Array(x, y, z, _*) = arr
println("x=" + x + ", y=" + y + ", z=" + z)
}
}