Scala 模式匹配

1. 基本模式匹配

  1. Java中: 对一个值进行条件判断,返回针对不同的条件进行不同的处理:switch case

  2. scala中:

    变量 match {
      case value1 ==> 代码1
      case value2 ==> 代码2
      ....
      case _ => 代码N
    }
    
  3. 一个栗子

    import scala.util.Random
    /**
     * Author: 3zZ.
     * Date: 2020/1/10 12:10 上午
     */
    object MatchApp extends App {
      val names = Array("a", "b", "c")
      val name = names(Random.nextInt(names.length))
      name match{
        case "a" => println(1)
        case "b" => println(2)
        case _ => println("不知道")
      }
      def judgeGrade(grade: String): Unit ={
        grade match{
          case "A" => println("Excellent..")
          case "B" => println("Good..")
          case "C" => println("Just so so..")
          case _ => println("u need worker harder")
        }
      }
      judgeGrade("A")
      judgeGrade("C")
      judgeGrade("G")
    }
    // 输出结果
    1
    Excellent..
    Just so so..
    u need worker harder
    

2. 加条件

  • 双重过滤

    /**
     * Author: 3zZ.
     * Date: 2020/1/10 12:10 上午
     */
    object MatchApp extends App {
      def judgeGrade(name:String, grade: String): Unit ={
        grade match{
          case "A" => println("Excellent..")
          case "B" => println("Good..")
          case "C" => println("Just so so..")
          case _ if(name == "lisi") => println(name + " u need worker harder")
          case _  => println("u need worker harder")
        }
      }
      judgeGrade("zhangsan","D")
      judgeGrade("lisi","D")// 双重过滤
    }
    // 输出
    u need worker harder
    lisi u need worker harder
    

3. 数组(Array)中的过滤

/**
 * Author: 3zZ.
 * Date: 2020/1/10 12:10 上午
 */
object MatchApp extends App {
  def greeting(array: Array[String]): Unit = {
    array match {
      case Array("zhangsan") => println("hello zhangsan")
      case Array(x, y) => println("hi: " + x +" and " + y)
      case Array("zhangsan", _*) => println("hi: zhangsan and other")
      case _ => println("hi everybody")
    }
  }
  greeting(Array("zhangsan"))
  greeting(Array("zhangsan", "lisi"))
  greeting(Array("zhangsan", "lisi", "wangwu"))
}
// 返回结果
hello zhangsan
hi: zhangsan and lisi
hi: zhangsan and other

4. List中的过滤

/**
 * Author: 3zZ.
 * Date: 2020/1/10 12:10 上午
 */
object MatchApp extends App {
  def greeting(list: List[String]): Unit = {
    list match {
      case "zhangsan" :: Nil => println("Hi: zhangsan")
      case x :: y :: Nil => println("Hi:" + x + " , " + y)
      case "zhangsan"::tail => println("Hi: zhangsan and others")
      case _ => println("hi: everyone")
    }
  }
  greeting(List("zhangsan"))
  greeting(List("zhangsan","lisi"))
  greeting(List("zhangsan","lisi","wangwu"))
  greeting(List("wangwu","zhangsan","lisi"))
}
// 返回
Hi: zhangsan
Hi: zhangsan , lisi
Hi: zhangsan and others
hi: everyone

5. 类型匹配

/**
 * Author: 3zZ.
 * Date: 2020/1/10 12:10 上午
 */
object MatchApp extends App {
  def matchType(obj: Any): Unit = {
    obj match {
      case x: Int => println("Int")
      case s:String => println("String")
      case m:Map[_,_] => m.foreach(println)
      case _ => println("other type")
    }
  }
  matchType(1)
  matchType("1")
  matchType(Map("name" -> "a"))
  matchType(1f)
}
// 返回
Int
String
(name,a)
other type

6. 异常处理

/**
 * Author: 3zZ.
 * Date: 2020/1/10 1:26 上午
 */
object ExceptionApp extends App {
  try {
    val i = 10 / 0
    println(i)
  } catch {
    case e: ArithmeticException => println("除数不能为0")
    case e: Exception => println(e.getMessage)
  } finally {
    // 释放资源
  }
}
  • 在catch中判断异常
  • 在finally中释放资源

7. Case Class中的匹配

/**
 * Author: 3zZ.
 * Date: 2020/1/10 1:26 上午
 */
object ExceptionApp extends App {
  def caseclassMatch(person: Person): Unit ={
    person match{
      case CTO(name, floor) => println("CTO name is "+name+" ,floor: "+ floor)
      case Employee(name, floor) => println("Employee name is "+name+" ,floor: "+ floor)
      case _ => println("other")
    }
  }
  class Person
  case class CTO(name:String, floor:String) extends Person
  case class Employee(name:String, floor:String) extends Person
  case class Other(name:String) extends Person
  caseclassMatch(CTO("3zz","22"))
  caseclassMatch(Employee("zhangsan", "2"))
  caseclassMatch(Other("lisi"))
}
// 返回
CTO name is 3zz ,floor: 22
Employee name is zhangsan ,floor: 2
other