模式匹配是检查某个值(value)是否匹配某一个模式的机制,一个成功的匹配同时会将匹配值解构为其组成部分。它是Java中的switch语句的升级版,同样可以用于替代一系列的 if/else 语句。

语法

一个模式匹配语句包括一个待匹配的值,match关键字,以及至少一个case语句。

  1. import scala.util.Random
  2. val x: Int = Random.nextInt(10)
  3. x match {
  4. case 0 => "zero"
  5. case 1 => "one"
  6. case 2 => "two"
  7. case _ => "other"
  8. }

上述代码中的val x是一个0到10之间的随机整数,将它放在match运算符的左侧对其进行模式匹配,match的右侧是包含4条case的表达式,其中最后一个case _表示匹配其余所有情况,在这里就是其他可能的整型值。

match表达式具有一个结果值

  1. def matchTest(x: Int): String = x match {
  2. case 1 => "one"
  3. case 2 => "two"
  4. case _ => "other"
  5. }
  6. matchTest(3) // other
  7. matchTest(1) // one

这个match表达式是String类型的,因为所有的情况(case)均返回String,所以matchTest函数的返回值是String类型。

案例类(case classes)的匹配

案例类非常适合用于模式匹配。

  1. abstract class Notification
  2. case class Email(sender: String, title: String, body: String) extends Notification
  3. case class SMS(caller: String, message: String) extends Notification
  4. case class VoiceRecording(contactName: String, link: String) extends Notification

Notification 是一个虚基类,它有三个具体的子类Email, SMSVoiceRecording,我们可以在这些案例类(Case Class)上像这样使用模式匹配:

  1. def showNotification(notification: Notification): String = {
  2. notification match {
  3. case Email(sender, title, _) =>
  4. s"You got an email from $sender with title: $title"
  5. case SMS(number, message) =>
  6. s"You got an SMS from $number! Message: $message"
  7. case VoiceRecording(name, link) =>
  8. s"you received a Voice Recording from $name! Click the link to hear it: $link"
  9. }
  10. }
  11. val someSms = SMS("12345", "Are you there?")
  12. val someVoiceRecording = VoiceRecording("Tom", "voicerecording.org/id/123")
  13. println(showNotification(someSms)) // prints You got an SMS from 12345! Message: Are you there?
  14. println(showNotification(someVoiceRecording)) // you received a Voice Recording from Tom! Click the link to hear it: voicerecording.org/id/123

showNotification函数接受一个抽象类Notification对象作为输入参数,然后匹配其具体类型。(也就是判断它是一个EmailSMS,还是VoiceRecording)。在case Email(sender, title, )中,对象的sendertitle属性在返回值中被使用,而body属性则被忽略,故使用代替。

模式守卫(Pattern gaurds)

为了让匹配更加具体,可以使用模式守卫,也就是在模式后面加上if <boolean expression>

  1. def showImportantNotification(notification: Notification, importantPeopleInfo: Seq[String]): String = {
  2. notification match {
  3. case Email(sender, _, _) if importantPeopleInfo.contains(sender) =>
  4. "You got an email from special someone!"
  5. case SMS(number, _) if importantPeopleInfo.contains(number) =>
  6. "You got an SMS from special someone!"
  7. case other =>
  8. showNotification(other) // nothing special, delegate to our original showNotification function
  9. }
  10. }
  11. val importantPeopleInfo = Seq("867-5309", "jenny@gmail.com")
  12. val someSms = SMS("867-5309", "Are you there?")
  13. val someVoiceRecording = VoiceRecording("Tom", "voicerecording.org/id/123")
  14. val importantEmail = Email("jenny@gmail.com", "Drinks tonight?", "I'm free after 5!")
  15. val importantSms = SMS("867-5309", "I'm here! Where are you?")
  16. println(showImportantNotification(someSms, importantPeopleInfo))
  17. println(showImportantNotification(someVoiceRecording, importantPeopleInfo))
  18. println(showImportantNotification(importantEmail, importantPeopleInfo))
  19. println(showImportantNotification(importantSms, importantPeopleInfo))

case Email(sender, , ) if importantPeopleInfo.contains(sender)中,除了要求notificationEmail类型外,还需要sender在重要人物列表importantPeopleInfo中,才会匹配到该模式。

仅匹配类型

也可以仅匹配类型,如下所示:

  1. abstract class Device
  2. case class Phone(model: String) extends Device{
  3. def screenOff = "Turning screen off"
  4. }
  5. case class Computer(model: String) extends Device {
  6. def screenSaverOn = "Turning screen saver on..."
  7. }
  8. def goIdle(device: Device) = device match {
  9. case p: Phone => p.screenOff
  10. case c: Computer => c.screenSaverOn
  11. }

当不同类型对象需要调用不同方法时,仅匹配类型的模式非常有用,如上代码中goIdle函数对不同类型的Device有着不同的表现。一般使用类型的首字母作为case的标识符,例如上述代码中的pc,这是一种惯例。

密封类

特质(trait)和类(class)可以用sealed标记为密封的,这意味着其所有子类都必须与之定义在相同文件中,从而保证所有子类型都是已知的。

  1. sealed abstract class Furniture
  2. case class Couch() extends Furniture
  3. case class Chair() extends Furniture
  4. def findPlaceToSit(piece: Furniture): String = piece match {
  5. case a: Couch => "Lie on the couch"
  6. case b: Chair => "Sit on the chair"
  7. }

这对于模式匹配很有用,因为我们不再需要一个匹配其他任意情况的case

备注

Scala的模式匹配语句对于使用案例类(case classes)表示的类型非常有用,同时也可以利用提取器对象(extractor objects)中的unapply方法来定义非案例类对象的匹配。