If all the cases do not match, the case _ branch will be executed, similar to the default statement in Java. If there is no case _ branch at this time, a MatchError will be thrown.
In each case, there is no need to use the break statement, and the case is automatically interrupted.
The match case statement can match any type, not just literals.
=> The following code block, the code before the next case statement is executed as a whole, can be enclosed in {} or not enclosed.
Mode guard
The case condition also specifies the judgment condition.
val num3 =-10// 模式守卫def myAbs(num:Int)= num3 match{
case i:Intif i >=0=> i
case j:Intif j <0=>-j
}
println(myAbs(num3))
def main(args: Array[String]):Unit={
for(arr <- Array(Array(0), Array(1,0), Array(0,1,0), Array(1,1,0), Array(1,1,0,1), Array("hello",90))){
// 对一个数组集合进行遍历val result = arr match{
case Array(0)=>"0"//匹配Array(0) 这个数组case Array(x, y)=> x +","+ y //匹配有两个元素的数组,然后将将元素值赋给对应的x,ycase Array(0, _*)=>"以0开头的数组"//匹配以0开头的数组case _ =>"something else"}
println("result = "+ result)}}
Match list
for(list <- Array(List(0), List(1,0), List(0,0,0), List(1,0,0), List(88))){
val result = list match{
case List(0)=>"0"//匹配List(0)case List(x, y)=> x +","+ y //匹配有两个元素的Listcase List(0, _*)=>"0 ..."case _ =>"something else"}
println(result)}val list: List[Int]= List(1,2,5,6,7)
list match{
case first :: second :: rest => println(first +"-"+ second +"-"+ rest)case _ => println("something else")}
Matching tuple
//对一个元组集合进行遍历for(tuple <- Array((0,1),(1,0),(1,1),(1,0,2))){
val result = tuple match{
case(0, _)=>"0 ..."//是第一个元素是0的元组case(y,0)=>""+ y +"0"// 匹配后一个元素是0的对偶元组case(a, b)=>""+ a +" "+ b
case _ =>"something else"//默认}
println(result)}
The bottom layer of the sample class will automatically implement the unapply method to obtain the properties of the object.
object Scala05_Match {
def main(args: Array[String]):Unit={
val stu =new Student05("lisi",18)val res = stu match{
case Student05("lisi",18)=>truecase _ =>false}
println(res)}}// 样例类底层会自动实现unapply方法,获取对象的属性caseclass Student05(var name:String,var age:Int){
}