一 模式匹配

基础语法

Java

一般匹配类型是整数或字符串

  1. int flag = 1
  2. String res = ""
  3. swich(flag){
  4. case 1 :
  5. res = "1";
  6. break;
  7. case 2 :
  8. res = "2";
  9. break;
  10. default :
  11. res = "3";
  12. break;
  13. }

Scala

  1. val op : Any = ops match {
  2. case "+" => a+b
  3. case "-" => a-b
  4. case "*" => a*b
  5. case "/" => a/b
  6. case _ => "没有该操作" //默认
  7. }

案例应用

  1. def ops(op:String,a:Int,b:Int): Any = op match {
  2. case "+" => a+b
  3. case "-" => a-b
  4. case "*" => a*b
  5. case "/" => a/b
  6. case _ => "没有该操作" //默认
  7. }
  8. println(ops("++",1,3))