模式匹配
Scala 模式匹配比较灵活多变, 支持非常多的方式. 网上资料, 不管是官网的tour 还是别的地方都比较分散, 这里做一个整合.
基本语法
基本语法比较简单, 不做过多介绍.
x match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "many"
}
匹配方法
类匹配
可以理解为匹配类定义, 且可以获取相应变量
abstract class Notification
case class Email(sender: String, title: String, body: String) extends Notification
case class SMS(caller: String, message: String) extends Nofication
case class VoiceRecording(contactName: String, link: String) extends Notification
notification match{
case Email(sender, title, _) => s"You got an email from $sender with title: $title"
case SMS(number, message) => s"You got an SMS from..."
case VoiceRecording(name, link) => s"$name, $link"
}
类型匹配
match on type only. 可以匹配泛型. 更详细参见 这里
notification match{
case e: Email =>
case s: SMS =>
case v: VoiceRecording =>
case list: List[_]