1、模式匹配
可幾乎可以匹配所有的的
object MatchCaseDemo extends App {
private val p = new MatchCaseDemoClass
private val arr = Array(1, "allen", p, 2, Array(1, 3, 5, 7), 3.5, 5, 6, 78, List(3, -1), (78, 79, 80))
println(arr.toBuffer)
for (a <- arr) {
a match {
case "allen" => println("it is allen")
case x: Int if (x >= 3) => println("The number is" + x)
case y: MatchCaseDemoClass => println("it is MatchCaseDemoClass")
case Array(x1, x2, x3, x4) => println(x2)
case Array(0) => println("only 0")
case 0 :: Nil => println("only 0")
case x :: y :: Nil => println(s"x: $x y: $y")
case 0 :: tail => println("0...")
case _ => println("other")
}
}
}
class MatchCaseDemoClass {
var name: String = "allen"
}
/*
ArrayBuffer(1, allen, cn.huawei.scala.MatchCaseDemoClass@2d3fcdbd, 2, [I@617c74e5, 3.5, 5, 6, 78, List(3, -1), (78,79,80))
other
it is allen
it is MatchCaseDemoClass
other
3
other
The number is5
The number is6
The number is78
x: 3 y: -1
other
*/
2、利用Option來查看是否可以獲取到值
object OptionDemo extends App {
private val map1 = Map("allen" -> 20, "tom" -> 18)
val age1 = map1.get("allen") match {
case Some(i) => i //Some表示包含了某個值
case None => 0 //表示沒有包含某個值
}
println(age1)
}
3、偏函數
被包在花括號內沒有match的一組case語句是一個偏函數,它是PartialFunction[A, B]的一個實例,A代表參數類型,B代表返回類型,常用作輸入模式匹配
object OptionDemo extends App {
private val map1 = Map("allen" -> 20, "tom" -> 18)
val age1 = map1.get("allen") match {
case Some(i) => i //Some表示包含了某個值
case None => 0 //表示沒有包含某個值
}
println(age1)
def f1: PartialFunction[String, Int] = {
case "allen" => 23
case "tom" => 20
case _ => 18
}
def f2(name: String): Int = name match {
case "allen" => 23
case "tom" => 20
case _ => 18
}
println(f1("allen"))//調用apply方法,從匹配到的模式計算函數值
println(f1.isDefinedAt("tom"))//調用isDefinedAt方法在輸入至少匹配一個模式是返回true
println(f2("allen"))
}