def cal(exp: String): Int = { val add = "+" val result = 1 exp match { case "+" => result + 2 //常量模式仅仅匹配自身 case "-" => result - 2 case "*" => result * 2 case "/" => result / 2 case add => result + 2 //变量模式可以匹配任意对象 case _ => result //通配模式匹配任意对象 } }
//序列模式 def prtList(list: List[Int]) = list match { case List(0, _, _) => println("this is a list") //序列模式,可以匹配List或者Array case List(1, _*) => println("this is a list, too") //匹配一个不指定长度的序列 case _ => println("other") }
//元组模式 def prtTuple(tup: Any) = tup match { case (0, _, _) => println("this is a tuple") //元组模式 case _ => println("other") }
//类型模式,可以用在类型测试和类型转换 def prtType(x: Any) = x match { case s: String => s.length case m: Map[_, _] => m.size case _ => 1 }