Scala模式匹配

模式匹配
  Java:switch case 值 对一个值进行条件判断,返回针对不同的条件进行不同的处理
  Scala:match case 值/类型/集合

基本语法:
变量 match {
  case value1 => 代码1
  case value2 => 代码2
  .....
  case _ => 代码N
}


object MatchApp extends App {

  val names = Array("Akiho Yoshizawa", "YuiHatano", "Aoi Sola")
  val name = names(Random.nextInt(names.length))   //随机取一个名字

  name match {
    case "Akiho Yoshizawa" => println("吉老师...")
    case "YuiHatano" => println("波老师...")
    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("You need work harder...")
    }
  }

  judgeGrade("A")
  judgeGrade("C")
  judgeGrade("D")
}


加条件进行匹配:

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 + " , You are a good boy, but...")    //这里右多了一层判断
      case _ => println("You need work harder...")
    }
  }

  judgeGrade("zhangsan", "D")
  judgeGrade("lisi", "D") //双重过滤
}


Array模式匹配:
object MatchApp extends App {
  def greeting(array:Array[String]): Unit = {
    array match {
      case Array("zhangsan") => println("Hi:zhangsan")
      case Array(x,y) => println("Hi: " + x + " , " + y)
      case Array("zhangsan", _*) => println("Hi:zhangsan and other friends...")    //zhangsan开头的任意个的一个数组。
      case _ => println("Hi: everybody...")
    }
  }

  greeting(Array("zhangsan"))    //走第一个case
  greeting(Array("lisi", "wangwu"))    //走第二个case
  greeting(Array("zhangsan","lisi", "wangwu"))   //走第三个case
  greeting(Array("lisi", "zhangsan", "wangwu"))    //走第四个case
}


List模式匹配:
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 other friends...")
      case _ => println("Hi:everybody...")
    }
  }

  greeting(List("zhangsan"))   //走的第一个case
  greeting(List("lisi", "zhangsan"))   //走的第二个case
  greeting(List("zhangsan","lisi"))    //走的第二个case,先匹配上这个了。因为顺序的问题,所以没有做第三个case,而是走了第二个case。
  greeting(List("PK","zhangsan","lisi"))    //走的第四个case
}


类型匹配:Scala能根据类型做匹配

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)    //Int, 走的第一个case
  matchType("1")    //String,走的第二个case
  matchType(1f)    //other type ,走的第四个case
  matchType(Map("name" -> "PK"))    //(name,PK), 走的第三个case
}

Scala异常处理:
object ExceptionApp extends App {

  //IO
  val file = "test.txt"

  try{

    // open file
    // use file

    val i = 10/0    //是会报错的,不能被0除,需要用try catch。
    println(i)
  } catch {
    case e:ArithmeticException => println("除数不能为0..")
    case e:Exception => println(e.getMessage)
  } finally {
    //释放资源,一定能执行: close file
  }
}

这就是我们常用的一个处理步骤,把要处理的东西丢到try里面,然后在catch里面通过 case 这种方式把我们的异常给捕获到,该怎么处理就是业务逻辑层面的问题了。最后把释放资源写到finally就行了。


case class模式匹配: case class不用new的,直接就能使用。

object CaseClassApp extends App {
  def caseclassMatch(person:Person): Unit = {
    person match {
      case CTO(name,floor) => println("CTO name is: " + name + " , floor is : " + floor)
      case Employee(name,floor) => println("Employee name is: " + name + " , floor is : " + floor)
      case _ => println("other")
    }
  }
  class Person
  case class CTO(name:String, floor:String) extends Person
  case class Employee(name:String, floor:String) extend Person
  case class Other(name:String) extend Person

  caseclassMatch(CTO("PK", "22"))
  caseclassMatch(Employee("zhangsan", "2"))
  caseclassMatch(Other("other"))
}


Some、None 模式匹配:

object CaseClassApp extends App {

  val grades = Map("PK"->"A", "zhangsan"->"C")

  def getGrade(name:String): Unit = {
    val grade = grades.get(name)

    grade match {
      case Some(grade) => println(name + ": your grade is :" + grade)
      case None => println("sorry....")
    }
  }
  getGrade("zhangsan")   //zhangsan: your grade is : C
  getGrade("PK")    //PK: your grade is : A
  getGrade("lisi")    //sorry....
}

 

上一篇:Redis系列三:redis支持的数据类型


下一篇:原来Linux可以这么简单,超详细Linux基本入门讲解