模式匹配Match...case...

模式匹配:即if…else…平铺式表达,用match关键字匹配,用case限定模式,case _代表不匹配的情况下返回值
模式守卫:即模式匹配中可以使用if条件限定范围,match{case … if … => …}

match{case 条件1 =>{函数体};case 条件2 =>{函数体};case _ =>{函数体}}

  • 例:定义一个计算方法
object Main extends App {
    val a:Double = 1
    val b:Double = 2
    def yunsuan(op:Any):Double = op match{
        case "+" => a+b
        case "-" => a-b
        case "*" => a*b 
        case "/" => a/b 
        case op:Int if op > 0 && op<=10 => op
        case op:Int if op > 10 || op<0 => -op
        case _ => 0
    }
    println("1:" + yunsuan(1))
    println("-1:" + yunsuan(-1))
    println("乘积:" + yunsuan("*"))
    println("商:" + yunsuan("/"))
}
11.0
-11.0
乘积:2.0
商:0.5
匹配字符串
object Main extends App {
    val a = "a"
    val b = "b"
    def matchtest(op:Any) = op match{
        case "+" => a+b
        case "-" => a + "-" + b
        case op:Int if op >= 1 && op<=10 => "true"
        case op:Int if op < 1 => "false"
        case _ => "其他"
    }
    println("1:" + matchtest(1))
    println("-1:" + matchtest(-1))
    println("a合并b:" + matchtest("+"))
    println("a-b:" + matchtest("-"))
    println(matchtest(".."))
}
1true
-1false
a合并b:ab
a-b:a-b
其他
匹配类型
object Main extends App {
    def match_test1(op:Any) = op match{
        case i:List[Int] => "list:" + i
        case j:Array[String] => "Array:" + j.mkString(",")
        case p => "else:" + p
    }
    println(match_test1(List(1,2,3)))
    println(match_test1(List("a","b")))
    println(match_test1(Array("alice","cindy"))) 
    println(Array(1,2))
}
/*
*参数i的List类型存在泛型擦除,所以即使设置了List的泛型为Int,文本类List也可以生效
*参数j的Array类型不存在泛型擦除,所以只有文本类型的Array可以生效
*/
list:List(1, 2, 3)
list:List(a, b)
Array:alice,cindy
[I@3fee733d
  • 例1:匹配数组、列表、元组等
object Main extends App {
    for (i <- List(Array(0,1),Array(1,0),Array(1,1,0),Array(1,2,3,4),List(2),(1,2,3))){
		val result = i match{
			case Array(0,_*) => "以0开头的数组" //在列表和数组中,_*代表任意值
			case Array(x,y) => "两元素数组:" + x + "," + y
			case List(m,1,n) => "中间为1的三元素数组"
			case List(j) => "List:" + j 
			case (_,2,x) => "以任意值开头的三元素元组:" + i //在元组中,_代表任意值
			case _ => "else"
		}
	    println(result)
	}
}0开头的数组
两元素数组:1,0
else
else
List:2
以任意值开头的三元素元组:(1,2,3)
  • 例2:列表的元素追加判断
object Main extends App {
    val list = List(1,2,3,4,5)
	list match{
		case one::two::three => println(s"list结果-first:${one},second:${two},rest:${three}") //如果列表由两个元素追加而成,则输出追加的元素与剩余列表
		case _ => println("else")
	}
	val list1 = List(1)
	list1 match{
		case one::two::three => println(s"list1结果-first:${one},second:${two},rest:${three}") //列表只有1个元素,无法由三个元素组成,所以不符合条件
		case _ => println("list1结果-else")
	}
	val list2 = List(1,2)
	list2 match{
		case one::two::three => println(s"list2结果-first:${one},second:${two},rest:${three}") //列表只有两个元素,所以第三个元素输出为空列表
		case _ => println("else")
	}
}
list结果-first:1,second:2,rest:List(3, 4, 5)
list1结果-else
list2结果-first:1,second:2,rest:List()
  • 例3:对列表的元素进行匹配后,再map处理
object Main extends App {
    val list = List(("a",1),("b",2),3)
    println(list)
    //若list的元素为键值对,则做处理,否则返回原来的值
    val list1 = list.map(i => i match{
        case (m:String,n:Int) => (m,n * 2)
        case _ => i
    })
    println(list1)
}
List((a,1), (b,2), 3)
List((a,2), (b,4), 3)
匹配对象与样例类

对象需要通过方法来实现类的实例化。样例类则直接将类实例化,样例类的使用非常方便。

  • 例1:对象匹配
object Main extends App {
   val student = Student("cindy",18) //新建变量,对象传参,返回实例内容
   
   //针对对象实例进行匹配
   val result = student match{
       case Student("cindy",18) => student.name + "," + student.age
       case _ => "else"
   }
   println(result)

}
//类
class Student(val name:String,val age:Int)
//伴生对象:将类转化为一个实际类型的对象,再用match去匹配这个类型的值
object Student{
	def apply(name:String,age:Int) = new Student(name,age) //用apply方法引入对象属性,但这实质是对类Student的引用,而不返回对象实例
	def unapply(i:Student):Option[(String,Int)] = { //用unapply方法,拆解对象属性,使之可以作为对象实例参与match匹配
		if (i == null){
			None
		}else{
			Some((i.name,i.age))
		}
	}
}
cindy,18
  • 例2:样例类匹配
object Main extends App {
   val student = Student("alice",18) //新建变量,对象传参,返回样例类的实例内容,不需要关键字new
   
   //针对对象实例进行匹配
   val result = student match{
       case Student("cindy",18) => student.name + "," + student.age
       case _ => "else"
   }
   println(result)

}
//样例类:即把apply与unapply方法全部封装到一起,直接产生实例对象
case class Student(name:String,age:Int) //参数不需要加val

你可能感兴趣的:(Scala,scala)