1.常量匹配
def constantMatch(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
def constantMathTest()={
println(constantMatch(1))
println(constantMatch(5))
}
输出结果
one
many
2.列表匹配
def sequenceMatch(x: List[Int]): String = x match {
case List(5, _, _) => "匹配5元素开头的三元素列表"
case List(1, _*) => "匹配以1开头任意数目的列表"
case _ => "其他"
}
def sequenceMathTest() = {
println(sequenceMatch(List(5, 8, 9)))
println(sequenceMatch(List(5, 8, 9, 1)))
println(sequenceMatch(List(1, 5, 8, 9)))
}
输出结果
匹配5元素开头的三元素列表
其他
匹配以1开头任意数目的列表
3.构造器匹配
def constructorMatch(x: Person): String = x match {
case Person("tom", 12) => "name:tom,age:12"
case Person(first, 49) => s"name:$first,age:49"
case _ => "other"
}
def constructorMatchTest() = {
println(constructorMatch(Person("tom", 12)))
println(constructorMatch(Person("tom", 49)))
println(constructorMatch(Person("tom", 49)))
}
输出结果
name:tom,age:12
name:tom,age:49
name:tom,age:49
4.元组匹配
def tupleMatch(x: Any): String = x match {
case (a, b) => s"匹配二元组,元素为$a,$b"
case (a, b, c) => s"匹配三元组,元素为$a,$b,$c"
case _ => "other"
}
def tupleMatchTest() = {
println(tupleMatch(Tuple2(1, 2)))
println(tupleMatch(Tuple3(1, 2, 3)))
}
输出结果
匹配二元组,元素为1,2
匹配三元组,元素为1,2,3
5.类型匹配
def typeMatch(x: Any): String = x match {
case s: String => s"字符串类型匹配 $s"
case s: Int => s"整形匹配 $s"
case Person(name, age) => s"string type match $name,$age"
case _ => "other"
}
def typeMatchTest() = {
println(typeMatch("字符串"))
println(typeMatch(5))
println(Person("tom", 25))
}
运行结果
字符串类型匹配 字符串
整形匹配 5
Person(tom,25)
if模式匹配 约束
利用if语句附加更多的条件达到更细致的模式匹配
def ifMatch(x: (Int, Int)): String = x match {
case (x1, x2) if x2 == 0 => s"非法的分数表示"
case (x1, x2) => s"合法的分数表示:$x1/$x2"
}
def ifMatchTest() = {
println(ifMatch(2, 0))
println(ifMatch(3, 8))
}
运行结果
非法的分数表示
合法的分数表示:3/8
本文介绍了Scala中的模式匹配概念,包括常量匹配、列表匹配、构造器匹配、元组匹配及类型匹配等,并通过实例展示了每种匹配方式的具体应用。
1000

被折叠的 条评论
为什么被折叠?



