Scala模式匹配

类似于java中的switch case语法。

scala的模式不仅可以对值进行匹配,还可以对类型进行匹配。

而且对于Spark来说,Scala的模式匹配功能也是极其重要的。

1、模式匹配基础语法

match case语法最基本的应用,就是对变量的值进行模式匹配。

1.1 基本用法

//成绩评价
object test {
  def main(args: Array[String]): Unit = {
    def stu_score(score:String)={
      score match {
        case "A" => println("excellent")
        case "B"=> println("good")
        case "C" => println("soso")
        case _ => println("you need work harder")
      }
    }
    stu_score("A")
  }
}

1.2 在模式匹配中使用if守卫–双重过滤

//成绩评价
object test {
  def main(args: Array[String]): Unit = {
    def stu_score2(name:String,score:String)={
      score match {
        case "A" => println("excellent")
        case "B"=> println("good")
        case "C" => println("soso")
        case _ if name=="mary" => println(name+" you need work harder")
      }
    }
    stu_score2("mary","D") //输出:mary you need work harder
  }
}    

1.3 在模式匹配中进行变量赋值

//成绩评价
object test {
  def main(args: Array[String]): Unit = {
    def stu_score3(name:String,score:String)={
      score match {
        case "A" => println("excellent")
        case "B"=> println("good")
        case "C" => println("soso")
        case _ if name=="mary" => println(name+" you need work harder")
        case _score =>println("your score is "+_score)
      }
    }
    stu_score3("leo","F") //输出:your score is F
  }
}    

2、对类型进行模式匹配

Scala的模式匹配一个强大之处就在于,可以直接匹配类型,而不是值!!!这点是java的switch case绝对做不到的。

理论知识:对类型如何进行匹配?其他语法与匹配值其实是一样的,但是匹配类型的话,就是要用“case 变量: 类型 => 代码”这种语法,而不是匹配值的“case 值 => 代码”这种语法。

//异常处理
def processException(e:Exception): Unit ={
      e match {
        case e1:IllegalArgumentException=> println("you have illegal arguments! exception is: " + e1)
        case e2:FileNotFoundException => println("cannot find the file you need read or write!, exception is: " + e2)
        case e3: IndexOutOfBoundsException => println("you got an error while you were doing IO operation! exception is: " + e3)
        case _: Exception => println("cannot know which exception you have!" )
      }
    }
    processException(new IndexOutOfBoundsException("IndexOutOfBounds"))

3、对Array和List的元素进行模式匹配

//对朋友打招呼
//Array
def greeting(arr: Array[String]) {
  arr match {
    case Array("Leo") => println("Hi, Leo!")  //匹配一个元素
    case Array(girl1, girl2, girl3) => println("Hi, girls, nice to meet you. " + girl1 + " and " + girl2 + " and " + girl3) //匹配三个元素
    case Array("Leo", _*) => println("Hi, Leo, please introduce your friends to me.")
    case _ => println("hey, who are you?")
        }
      }
  greeting(Array("Leo")) //Hi, Leo!
  greeting(Array("Leo","lily","poly")) //Hi, girls, nice to meet you. Leo and lily and poly
  greeting(Array("Leo","lily")) //Hi, Leo, please introduce your friends to me.
  greeting(Array("poly","jack")) //hey, who are you?

//List


4、case class与模式匹配

//学校门禁,与样例类结合使用
case class Student(name:String,stu_id:Int)
case class Teacher(name:String,t_id:Int)
case class worker(name:String,work:String)

def entranceGuard(p:Any):Unit={
   p match {
     case Student(name,stu_id)=>println("hello! 学号:"+stu_id+",姓名:"+name+"同学,请进入!")
     case Teacher(name,t_id)=>println("hello! 教师编号:"+t_id+",姓名:"+name+"老师,请进入!")
     case worker(name,work)=>println(name+"员工,你的工作做是"+work+"请进入")
     case _=>println("陌生人禁止入校")
      }
}
entranceGuard(Student("张三",18))

5、Option与模式匹配

Scala有一种特殊的类型,叫做Option。Option有两种值,Some(x):表示实际的值,None:表示没有值

Option通常会用于模式匹配中,用于判断某个变量是有值还是没有值,这比null来的更加简洁明了。

Option的用法必须掌握,因为Spark源码中大量地使用了Option,比如Some(a)、None这种语法,因此必须看得懂Option模式匹配,才能够读懂spark源码。

//成绩查询
val grades=Map("Leo"->"A","Jack"->"B","Jen"->"C")
def getGrade(name:String): Unit ={
  val grade=grades.get(name) //输出:Some(B)
    grade match{
    case Some(grade)=>println("your grade is "+grade)
    case None =>println("Sorry,your grade information is not in the system")
    }
}
getGrade("Jack") //your grade is B
//使用Option类型,可以用来有效避免空引用(null)异常。也就是说,将来我们返回某些数据时,可以返回一个Option类型来替代。
def dvi(a:Double,b:Double):Option[Double] ={
      if (b!=0){
        Some(a/b)  //表示实际的值
      }else{
        None
      }
}
   //println(dvi(10, 1))  //输出:Some(10.0)
   var num=dvi(10,1)
   //模式匹配
   num match{
     case Some(a) =>println(a)
     case None=>println("??")
}
//输出:10.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值