@@ -66,8 +66,8 @@ case class VoiceRecording(contactName: String, link: String) extends Notificatio
66
66
```
67
67
def showNotification(notification: Notification): String = {
68
68
notification match {
69
- case Email(email , title, _) =>
70
- s"You got an email from $email with title: $title"
69
+ case Email(sender , title, _) =>
70
+ s"You got an email from $sender with title: $title"
71
71
case SMS(number, message) =>
72
72
s"You got an SMS from $number! Message: $message"
73
73
case VoiceRecording(name, link) =>
@@ -81,15 +81,15 @@ println(showNotification(someSms)) // prints You got an SMS from 12345! Message
81
81
82
82
println(showNotification(someVoiceRecording)) // you received a Voice Recording from Tom! Click the link to hear it: voicerecording.org/id/123
83
83
```
84
- ` showNotification ` 函数接受一个抽象类` Notification ` 对象作为输入参数,然后匹配其具体类型。(也就是判断它是一个` Email ` ,` SMS ` ,还是` VoiceRecording ` )。在` case Email(email , title, _) ` 中,对象的` email ` 和` title ` 属性在返回值中被使用,而` body ` 属性则被忽略,故使用` _ ` 代替。
84
+ ` showNotification ` 函数接受一个抽象类` Notification ` 对象作为输入参数,然后匹配其具体类型。(也就是判断它是一个` Email ` ,` SMS ` ,还是` VoiceRecording ` )。在` case Email(sender , title, _) ` 中,对象的` sender ` 和` title ` 属性在返回值中被使用,而` body ` 属性则被忽略,故使用` _ ` 代替。
85
85
86
86
## 模式守卫(Pattern gaurds)
87
87
为了让匹配更加具体,可以使用模式守卫,也就是在模式后面加上` if <boolean expression> ` 。
88
88
```
89
89
90
90
def showImportantNotification(notification: Notification, importantPeopleInfo: Seq[String]): String = {
91
91
notification match {
92
- case Email(email , _, _) if importantPeopleInfo.contains(email ) =>
92
+ case Email(sender , _, _) if importantPeopleInfo.contains(sender ) =>
93
93
"You got an email from special someone!"
94
94
case SMS(number, _) if importantPeopleInfo.contains(number) =>
95
95
"You got an SMS from special someone!"
@@ -111,7 +111,7 @@ println(showImportantNotification(importantEmail, importantPeopleInfo))
111
111
println(showImportantNotification(importantSms, importantPeopleInfo))
112
112
```
113
113
114
- 在` case Email(email , _, _) if importantPeopleInfo.contains(email ) ` 中,除了要求` notification ` 是` Email ` 类型外,还需要` email ` 在重要人物列表` importantPeopleInfo ` 中,才会匹配到该模式。
114
+ 在` case Email(sender , _, _) if importantPeopleInfo.contains(sender ) ` 中,除了要求` notification ` 是` Email ` 类型外,还需要` sender ` 在重要人物列表` importantPeopleInfo ` 中,才会匹配到该模式。
115
115
116
116
117
117
## 仅匹配类型
0 commit comments