packagecom.learnScala.day17
/**
* 模式匹配的功能类似于Java的switch,但是比Switch更灵活,更强大
* Created by zhuleqi on 2017/3/25.
*/
objectday17 {
defmain(args: Array[String]): Unit = {
caseAsSwitch('+')
caseAsSwitch('m')
println("==============")
caseObject(1.0)
caseObject("1.0")
caseObject(this)
println("==============")
caseArray(Array(0))
caseArray(Array(0,1))
caseArray(Array(0,1,2,3))
caseArray(Array(1,2,3,4))
println("==============")
caseList(List(0))
caseList(List(0,1))
caseList(List(0,1,2,3,4))
caseList(List(1,2,3,4,5))
println("==============")
caseTuple((0,1))
caseTuple((1,0))
caseTuple((0,0))
caseTuple((2,3))
}
/**
* 模式匹配 可以像Java中的switch一样,
*@param ch
*/
defcaseAsSwitch(ch:Char): Unit ={
chmatch{
case'+'=>println("+")
case'-'=>println("-")
case_=>println("other char")
}
}
/**
* 模式匹配可以用来判断值的类型
*@param value
*/
defcaseObject(value:Any): Unit ={
valuematch{
case_:Int =>println("value is Int")
case_:Double =>println("value is Double")
case_:String=>println("value is String")
case_ =>println("value is other type")
}
}
/**
* 对数组的模式匹配,实际上在内部使用了Array伴生类的unapplySeq(arr)方法返回一个序列,然后将返回的序列依次匹配,
* List,元组匹配类似
*@param arr
*/
defcaseArray(arr:Array[Int]): Unit ={
arrmatch{
//匹配数组的长度是1,并且是值是0的数组
caseArray(0)=>println(" only 0")
//匹配长度是2的数组,第一个值赋值给x,第二个值赋值给y
caseArray(x,y)=>println(x+","+y)
//匹配以首位是0的数组,长度不限
caseArray(0,_*)=>println("strart with 0")
case_=>println("other Arr")
}
}
defcaseList(list:List[Int]): Unit ={
listmatch{
//匹配List的长度是1,并且是值是0的数组
case0::Nil=>println("only 0")
//匹配长度是2的List,第一个值赋值给x,第二个值赋值给y
casex::y::Nil=>println(x+","+y)
//匹配以首位是0的List,长度不限
case0::tail=>println("start with o")
case_=>println("other List")
}
}
defcaseTuple(tuple:(Int,Int)): Unit ={
tuplematch{
//匹配第一个值是0
case(0,y)=>println("start 0 , y="+y)
//匹配第二个值是0
case(x,0)=>println("end 0,x="+x)
case_=>println(tuple._1+","+tuple._2)
}
}
}