val character = '1'character match {case '+' => println("this is +")case '-' => println("this is -")case ch => println("this is " + ch) // this is 1}
备注
上面代码中如果给定字符不是'+'或者'-',给定字符则会赋值给变量ch
也可以在守卫中使用变量:
val character = '5'character match {case '+' => println("this is +")case '-' => println("this is -")case ch if Character.isDigit(ch) => println("this is digit") // this is digit}
4. 类型模式
可以根据表达式的类型进行匹配:
val str:Any = "Hello World"str match {case s: String => println("this is string " + s) // this is string Hello Worldcase x: Int => println("this is integer " + x)case ch => println("this is other " + ch)}
def arrayMatch(arr:Array[String]) = arr match {caseArray("Hello") => println("the array only contain 'Hello'")caseArray(x,y) => println("the array contain two value " + x + " and " + y)caseArray(x,_*) => println("the array contain many values " + arr.mkString(","))case _ => println("the other array")}arrayMatch(Array("Hello")) // the array only contain 'Hello'arrayMatch(Array("Hello", "World")) // the array contain two value Hello and WorldarrayMatch(Array("Hello", "World", "Yoona")) // the array contain many values Hello,World,Yoona
同样也可以使用List表达式(或者使用::操作符)匹配列表:
def listMatch(list:List[String]) = list match {case"Hello" :: Nil => println("the list only contain 'Hello'")case x :: y :: Nil => println("the list contain two value " + x + " and " + y)case"Hello" :: tail => println("the list contain many values " + list)case _ => println("the other list")}listMatch(List("Hello")) // the list only contain 'Hello'listMatch(List("Hello", "World")) // the list contain two value Hello and WorldlistMatch(List("Hello", "World", "Yoona")) // the list contain many values List(Hello, World, Yoona)
同样也可以使用元组表示法匹配元组:
def pairMatch(t:Any) = t match {case("Hello", _) => println("the first value is 'Hello'")case(x, "Hello") => println("the first value is " + x + " and the second value is 'Hello'")case _ => println("the other tuple")}pairMatch(("Hello", "World")) // the first value is'Hello'pairMatch(("World", "Hello")) // the first value is World and the second value is'Hello'pairMatch(("Hello", "World", "Yoona")) // the other tuple