引用
我们今天接到一个开发任务,就是根据身份证号码,输出这个人的籍贯
ini
体验AI代码助手
代码解读
复制代码
package matchase
object matchase01 {
// 42 -> 湖北省
// 52 -> 西川省
def main(args: Array[String]): Unit = {
// val code = 52
// var province = ""
// if(code == 42) {
// province = "湖北省"
// } else if (code == 52) {
// province = "四川省"
// } else {
// province ="未知"
// }
// println(province)
val code = 12
val province = code match {
case 42 => "湖北省"
case 52 => "四川省"
case _ => "未知"
}
println(province)
}
}
match case的基本格式
格式如下
value match {
case pattern1 => result1
case pattern2 => result2
...
case patternN => resultN
case _ => 其他
练习
根据数值,输出对应的英文
代码
scala
体验AI代码助手
代码解读
复制代码
package matchase
object matchase02 {
def main(args: Array[String]): Unit = {
// 输入1,输出单词one
// 输入2,输出单词two
// 输入3,输出单词three
// 输入其他,输出单词other
// 1.从键盘获取数字
val code = 10
// 2.使用matchcase进行匹配
code match {
case 1 => println("one")
case 2 => println("two")
case _ => println("未知")
}
}
}
高阶匹配之元组元素数量
前面的匹配都是精准匹配:变量和值是相等的。但是呢,scala中的模式匹配的规则是非常强大的,不一定是精准的匹配值,还可以根据元组的元素的个数来匹配。
代码
scss
体验AI代码助手
代码解读
复制代码
package matchase
/*
math case
1.匹配精确值
2.匹配数据类型
3.匹配元素的个数
*/
object matchase03 {
def processValue(value:Any):Unit={
value match {
case x:Int => println("Int")
case x:String => println("String")
case _ => println("other")
}
}
def processNum(value:Any):Unit = {
value match {
case (a,b,c) => println("三个元素的元组")
case (x,y ) => println("两个元素的元组")
case _ => println("其他")
}
}
def main(args: Array[String]): Unit = {
// val obj = 10
// processValue(obj)
processNum((1,2))
processNum((1,2,3))
}
}
结果:
匹配数组元素的个数,元素的特征
scss
体验AI代码助手
代码解读
复制代码
package matchase
/*
math case
1.匹配精确值
2.匹配数据类型
3.匹配元素的个数
4.匹配数组元素的个数,元素的特征
*/
object matchase04 {
def matchArray(arr:Any):Unit ={
arr match {
case Array(x,y) => println("匹配到有两个元素的数组",x,y)
case Array(1,b,c) => println("匹配到有三个元素的数组,第一个元素师1")
case Array(a,b,c) => println("匹配到有三个元素的数组",a,b,c)
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)
matchArray(arr2)
matchArray(arr3)
}
}
结果:
计算面积
scss
体验AI代码助手
代码解读
复制代码
package matchase
/*
math case
1.匹配精确值
2.匹配数据类型
3.匹配元素的个数
4.匹配数组元素的个数,元素的特征
5.匹配案例1类
*/
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))
println(calculateArea(rectangle))
}
}
结果:
变量声明时的匹配
scss
体验AI代码助手
代码解读
复制代码
package matchase
/*
math case
1.匹配精确值
2.匹配数据类型
3.匹配元素的个数
4.匹配数组元素的个数,元素的特征
5.匹配案例1类
6.变量声明时的匹配
*/
object matchase06 {
def main(args: Array[String]): Unit = {
val arr = Array(11,22,33,4,5)
// 定义三个变量:x,y,z 保存数组中的前三个元素
val Array(x,y,z,_*) = arr
println(x,y,z)
}
}