模式匹配类型
一、匹配常量
在scala中,模式匹配可以匹配所有的字面量,包括字符串,字符,数字,布尔值等等
def describeConst(x:Any):String = x match {
case "str" => "匹配字符串"
case '+' => "匹配字符"
case 1 => "匹配整数"
case true => "匹配布尔值"
case a => s"匹配$a"
}
println(describeConst("str"))
println(describeConst('+'))
println(describeConst(1))
println(describeConst(true))
println(describeConst('-'))
二、匹配类型
def describeType(x:Any):String = x match {
case x:String => "匹配字符串"
case x:Char => "匹配字符"
case x:Int => "匹配整数"
case x:Boolean => "匹配布尔值"
case list:List[String] => "List" + list
case array:Array[Int] => "Array" + array.mkString("\t")
case a => s"匹配$a"
}
println(describeType("str"))
println(describeType('+'))
println(describeType(1))
println(describeType(true))
println(describeType(List("a","b","c")))
// 泛型擦除
println(describeType(List(1,2,3,4,5)))
println(describeType(Array(1,2,3,4,5)))
// array不存在泛型擦除
println(describeType(Array("1","2")))
三、匹配集合类型
代码:
for (arr <- List(
Array(0),
Array(1,0),
Array(0,1,0),
Array(1,1,0),
Array(2,3,7,15),
Array("hello","a",30)
)){
val result = arr match{
case Array(0) => "0"
case Array(1,0) => "Array(1,0)"
case Array(x,y) => "Array: " + x + ", " + y
case Array(0,_*) => "以0开头的数组"
case Array(x,1,z) => "中间为1的三元素数组"
case _ => "Something else"
}
println(result)
}
结果:
for(list <- List(
List(0),
List(1,0),
List(0,0,0),
List(1,1,0),
List(88),
List("hello")
)){
val result = list match {
case List(0) => "0"
case List(x,y) => "List(x,y): " + x + ", " + y
case List(0,_*) => "List(0,..."
case List(a) => "List(a):" + a
case _ => "something else"
}
println(result)
}
结果:
代码:
val list1 = List(1,2,5,7,24)
val list = List(24)
list match {
case first :: second :: rest => println(s"first:$first, second:$second , rest: $rest")
case _ => println("something else")
}
list1 match {
case first :: second :: rest => println(s"first:$first, second:$second , rest: $rest")
case _ => println("something else")
}
结果:
for (tuple <- List(
(0,1),
(0,0),
(0,1,0),
(0,1,1),
(1,23,56),
("hello",true,0.5)
)){
val result = tuple match {
case (a,b) => "" + a + ", " + b
case (0,_) => "(0, _)"
case (a,1,_) => "(a,1,_) " +a
case _ => "something else"
}
println(result)
}
结果:
在变量声明时匹配:
val (x,y) = (10,"hello")
println(s"x:$x,y:$y")
val List(first,second,_*) = List(23,15,9,78)
println(s"first:$first,second:$second")
val fir :: sec :: rest = List(23,15,9,78)
println(s"first:$fir,second:$sec,rest:$rest")
for推导式中进行模式匹配
将List的元素直接定义为元组,对变量赋值
val list = List(("a",12),("b",35),("c",27))
for ((word,count) <- list){
println(word + " " + count)
}
可以不考虑某个位置的变量,只遍历key或者value
val list = List(("a",12),("b",35),("c",27))
for ((word,_) <- list)
println(word)
可以指定某个位置的值必须是多少
val list = List(("a",12),("b",35),("c",27),("a",99))
for(("a",count) <- list){
println(count)
}
四、匹配对象及样例类
package scala
object User {
def main(args: Array[String]): Unit = {
val student = Student("alice",19)
val result = student match {
case Student("alice",19) => "Alice, 19"
case _ => "Else"
}
println(result)
}
case class Student(name:String,age:Int)
}