Scala 模式匹配
案例一: 模式匹配基本写法
如果能够匹配上、会自动执行case后面的语句、默认会有自动的break
如果都匹配不上、会自动执行 case _
=> 类似 java :
并且一个case里面可以写代码体 ,要添加{}
var oper = "+"
var res = 0
var num1 = 10
var num2 = 2
oper match {
case "+" => res = num1 + num2
case "-" => res = num1 - num2
case "*" => res = num1 * num2
case "/" => res = num1 / num2
case _ => println("error ")
}
println(res)
案例二:模式匹配(守卫)
守卫: 匹配所有的后面可以写条件 、一个模式匹配中可以同时存在多个匹配所有
for(c <- "+-3!"){
var t = 0
c match {
case '+' => t = 1