case class
scala编译器会自动为case class生成apply方法作为构造方法
case class的比较不是比较引用,而是比较每个字段的值。
case class的copy方法,可以改变要copy的某个字段
case class Message(sender: String, recipient: String, body: String)
val message4 = Message("A", "B", "Hello World")
val message5 = message4.copy(body="Hello Earth")
PATTERN MATCHING
scala中的模式匹配除了可以正向检查一个值是否和模式匹配,当匹配成功时,还可以逆向解析出这个值包含的元素如:
abstract class Notification
case class Email(sender: String, title: String, body: String) extends Notification
case class SMS(caller: String, message: String) extends Notification
case class VoiceRecording(contactName: String, link: String) extends Notification
def showNotification(notification: Notification): String = {
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 $number! Message: $message"
case VoiceRecording(name, link) =>
s"you received a Voice Recording from $name! Click the link to hear it: $link"
}
}
模式匹配后还可以加 if <boolean expression> 如:
case Email(sender, title, _) if sender == "vip" =>
s"You got an vip email from $sender with title: $title"