Scala中match case模式匹配

本文深入介绍了Scala中的模式匹配功能,包括基本语法、整型值匹配、带条件的匹配、数组和集合的匹配、任意类型的匹配及异常处理等内容,并通过具体示例展示了其强大的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 引言
  1. 了解java小伙伴的同学应该都知道在java中有switch...case语句,根据不同的值(switch(i))得到不同的结果(case是常量表达式),每个case字句后面可以有break结尾,最后一句default可有可无;
  2. 对于Scala中我们提供了更加强大的模式匹配match case,Scala的match case与Java的switch case最大的不同点在于,Java的switch case仅能匹配变量的值;而Scala的match case可以匹配各种情况,比如变量的类型、集合的元素、有值或无值等。
  3. 语法形式:
变量 match {
		case 值 => 代码
		case 值 => 代码
		case 值 => 代码
		....
		case _ => 代码
	}
2 整型值模式匹配实例
  //整行值模式匹配
  def test1(grade:String): Unit ={
    grade match {
      case "A" => println("Excellent...")
      case "B" => println("Good...")
      case "C" => println("Just so so...")
      case _ => println("You need to work harder...")
     }
  }

test1("A")
test1("D")

结果:
Excellent...
You need to work harder...
3 带有if条件的模式匹配
def test2(name:String,grade:String): Unit ={
    grade match {
      case "A" => println("Excellent...")
      case "B" => println("Good....")
      case "C" => println("Just so so....")
      case _ if name == "haha" => println(name + ", you are a good boy, but ...")
      case _ => println("You need to work harder....")
    }
  }
test2("zhangsan","B")
test2("haha","F")
test2("lisi","x")
结果:
Good....
haha, you are a good boy, but ...
You need to work harder....
4 数组的模式匹配
def test3(arr: Array[String]) {
  arr match {
      //只有一个hadoop元素
    case Array("Hadoop") => println("Hi, Hadoop")
    // 2个任意的元素
    case Array(x, y) => println("Hi:" + x + " and " + y )
    // zhangsan开头的任意多个元素
    case Array("zhangsan", _*) => println("Hi, zhangsan and others")
    case _ => println("hey, who are you?")
  }
}

test3(Array("hadoop"))
test3(Array("haha","hehe"))
test3(Array("zhangsan","lisi","wangwu"))
结果:
hey, who are you?
Hi:haha and hehe
Hi, zhangsan and others
5 集合的模式匹配
def test4(list: List[String]): Unit = {
  list match { // list = head + tail
      //只含有zhangsan一个元素
    case "zhangsan"::Nil => println("Hi: zhangsan")
      //任意两个元素
    case x::y::Nil => println("Hi:" + x + " , " + y)
      //第一个元素为haha的任意多个元素
    case "haha"::tail => println("Hi:haha and other friends...")
    case _ => println("Hi: everybody...")
  }
}

test4(List("zhangsan"))
test4(List("lengtouqing","tietouwa"))
test4(List("haha","hehe","heihei"))
结果:
Hi: zhangsan
Hi:lengtouqing , tietouwa
Hi:haha and other friends...
6 任意类型的模式匹配
def test5(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")
  }
}
test5(1)
test5("zhangsan")
test5(Map("01" -> "zhangsan"))
结果:
int
string
(01,zhangsan)
7 异常处理
//异常处理
  try {
    val i = 1/0
  } catch {
    case e:ArithmeticException => println("除数不能为0...")
    case e:Exception => println(e.getMessage)
  } finally {
    // io file
    println("finally.....")  // 是肯定执行的,通常用于做资源的释放使用
  }
  结果:
  除数不能为0...
  finally.....
8
  1. Scala中提供了一种特殊的类,用case class进行声明,中文也可以称作样例类。case class其实有点类似于Java中的JavaBean的概念。即只定义field,并且由Scala编译时自动提供getter和setter方法,但是没有method。
  2. case class的主构造函数接收的参数通常不需要使用var或val修饰,Scala自动就会使用val修饰(但是如果你自己使用var修饰,那么还是会按照var来)
  3. Scala自动为case class定义了伴生对象,也就是object,并且定义了apply()方法,该方法接收主构造函数中相同的参数,并返回case class对象
class Person
case class Teacher(name: String, subject: String) extends Person
case class Student(name: String, classroom: String) extends Person

def test6(p: Person) {
  p match {
    case Teacher(name, subject) => println("Teacher, name is " + name + ", subject is " + subject)
    case Student(name, classroom) => println("Student, name is " + name + ", classroom is " + classroom)
    case _ => println("Illegal access, please go out of the school!")
  }  
}
test6(Teacher("zhangsan","English"))
test6(Student("xiaoming","111"))
结果:
Teacher, name is zhangsan, subject is English
Student, name is xiaoming, classroom is 111

9 Option(Spark SQL用的非常多)
  1. Scala有一种特殊的类型,叫做Option。Option有两种值,一种是Some,表示有值,一种是None,表示没有值。
  2. Option通常会用于模式匹配中,用于判断某个变量是有值还是没有值,这比null来的更加简洁明了
  3. Option的用法必须掌握,因为Spark源码中大量地使用了Option,比如Some(a)、None这种语法,因此必须看得懂Option模式匹配,才能够读懂spark源码。
val grades = Map("zhangsan" -> "A", "lisi" -> "B", "wangwu" -> "C")

def getGrade(name: String) {
  val grade = grades.get(name)
  grade match {
    case Some(grade) => println("your grade is " + grade)
    case None => println("Sorry, your grade information is not in the system")
  }
}

    getGrade("zhangsan")
    getGrade("zhaoliu")
结果:
your grade is A
Sorry, your grade information is not in the system
case class SubmitTask(id:String, name:String)
case class HeartBeat(time:Long)
case object CheckTimeOutTask
// 结合Spark的实际代码理解
  val inputs = Array(CheckTimeOutTask, HeartBeat(10000), SubmitTask("001","task001"))
//使用Random类产生随机数
  inputs(Random.nextInt(inputs.length)) match {
    case SubmitTask(id, name) => {
      println("SubmitTask: " + id + " , " + name)
    }
    case HeartBeat(time) => {
      println("HeartBeat:" + time)
    }
    case CheckTimeOutTask => {
      println("CheckTimeOutTask")
    }
  }
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值