导入:根据一个值输出另一个与之对应的值
if else方法
val code = 42
var province = ""
if (code == 42) {
province = "湖北省"
} else if (code == 51){
province = "四川省"
}else {
province = "未知"
}
println(province) //湖北省
match case方法
val code= 12
val province = code match {
case 42 => "湖北省"
case 51 => "四川省"
case _ => "未知"
}
println(province) //未知
match case 的基本使用
输入1,输出单词one
输入2,输出单词two
输入3,输出单词three
输入其他,输出单词other
package matchase
object matchase02 {
def main(args: Array[String]): Unit = {
// 1.从键盘获取数字
val code= 10
// 2.使用matchcase进行匹配
code match {
case 1 => println("one")
case 2 => println("two")
case _ => println("未知")
}
}
}
注意:
1.如果能精准匹配(变量和值是相等的)成功,就会执行后面的代码
2.case _ 它表示可以匹配任意的内容。一定要放在match case 的最后一条
3.case _ 不能省略,如果匹配不成功,就会报错
match case 的高阶匹配
1.匹配数据类型 2.匹配精确值
package matchase
object matchase03 {
def processValue(value:Any): Unit = {
value match {
case x:Int => println("Int")
case x:String => println("String")
case _ => println("other")
}
}
def main(args: Array[String]): Unit = {
val obj = 10
processValue(obj) // Int
}
}
3.匹配元素的个数
package matchase
object matchase03 {
def processNum(value:Any): Unit = {
value match {
case (a,b,c) => println("三个元素的元组")
case(x,y) => println("两个元素的元组")
case _ => println("其他")
}
}
def main(args: Array[String]): Unit = {
processNum((1,2)) // 两个元素的元组
processNum((1,2,3)) // 三个元素的元组
}
}
4.匹配数组元素个数,元素特征
package matchase
object matchase04 {
def matchArray(arr:Any): Unit = {
arr match{
case Array(x,y) => println("匹配到有两个元素的数组",x,y)
case Array(a,b,c) => println("匹配到有三个元素的数组",a,b,c)
case Array(1,b,c) => println("匹配到有三个元素的数组,第一个元素是1")
case Array(10,_*) => println("第一个元素是10,元素的个数有任意个")
case _ => println("没有匹配到")
}
}
def main(args: Array[String]): Unit = {
val arr1 = Array(1,2,3)
val arr2 = Array(2,2,3)
val arr3 = Array(10,2,3,1)
matchArray(arr1) //(匹配到有三个元素的数组,1,2,3)
matchArray(arr2) //(匹配到有三个元素的数组,2,2,3)
matchArray(arr3) //第一个元素是10,元素的个数有任意个
}
}
5.匹配案例类
package matchase
object matchase05 {
case class Circle(r:Double) // 圆
case class Rectangle(w:Double,h:Double) // 矩形
def calculateArea(shape: Any): Double = {
shape match {
case Circle(r) => 3.14 * r * r
case Rectangle(w, h) => w * h
case _ => 0.0
}
}
def main(args: Array[String]): Unit = {
val circle = Circle(2.0)
val rectangle = Rectangle(2.0,3.0)
println(calculateArea(circle)) //12.56
println(calculateArea(rectangle)) //6.0
}
}
6.变量声明时的匹配
package matchase
object matchase06 {
def main(args: Array[String]): Unit = {
val arr = Array(11,22,33,4,5)
//定义3个变量:x,y,z 保存数组中的前三个元素的值
// val x = arr(0)
// val y = arr(1)
// val z = arr(2)
val Array(x,y,z,_*) = arr
println(x,y,z) //(11,22,33)
}
}