object InBuildControl{
def main(args: Array[String]): Unit = {
//常量模式:
//常量匹配
val site = "alibaba"
site match {
case "alibaba" =>println("alibaba") //这里这接匹配的变量的值。而不是匹配变量名。因此这里变量名可以小写。 //alibaba
}
val ALIBABa = "alibaba"
def mat(s:String): String ={
s match {
case ALIBABa => s // 要匹配常量名,条件和常量首字母都要大写。s 碰到大写开头的条件,就会去寻找条件所代表的值。
//本列中也就是说,s 会去寻找 ALIBABa所代表的值。也就是:alibaba。然后和s 的值 比较。
case _ => "no match"
}
}
println(mat("aeiou")) // no match
//变量匹配
def matt(e:String):Unit ={
e match{
case anything =>println(anything) //变量匹配其实就是把要匹配的对象用变量名代替,其实就是赋值。不存在比较的情况
//因此它 总是“匹配” 成功的。匹配条件中的变量一定要小写字母开头,不然,会被当成是常量匹配,然后去寻找常量所
//代表的值去比较,如果找不到相应的常量就会报错。
case _ => println("not match") //这个是通配符匹配,其实和变量匹配差不多.区别在于,变量匹配是一种赋值操作,
// 因此可以对变量进行操作。而通配符匹配则无法进行操作。它一般出现在所有匹配模式的最后,用于匹配任何对象。
//处理所有匹配不成功的默认情况。
}
}
matt("meme") // meme
}