caseclass Message(sender: String, recipient: String, body: String)val message1 = Message("guillaume@quebec.ca", "jorge@catalonia.es", "Ça va ?")println(message1.sender) // prints guillaume@quebec.camessage1.sender ="travis@washington.us"// this line does not compile
caseclass Message(sender: String, recipient: String, body: String)val message4 = Message("julien@bretagne.fr", "travis@washington.us", "Me zo o komz gant ma amezeg")val message5 = message4.copy(sender = message4.recipient, recipient ="claire@bourgogne.fr")message5.sender // travis@washington.usmessage5.recipient // claire@bourgogne.frmessage5.body // "Me zo o komz gant ma amezeg"
模式匹配
scala中使用match关键字和case来做模式匹配,类似java中的switch。
下面是一个简单的模式匹配的例子:
import scala.util.Randomval x: Int = Random.nextInt(10)x match {case0=>"zero"case1=>"one"case2=>"two"case _ =>"other"}
最后一个case _表示匹配其余所有情况。
match表达式是有值的,如下所示:
defmatchTest(x: Int): String = x match {case1=>"one"case2=>"two"case _ =>"other"}matchTest(3) // othermatchTest(1) // one
case也可以匹配case class, 如下所示:
abstractclass Notificationcaseclass Email(sender: String, title: String, body: String) extends Notificationcaseclass SMS(caller: String, message: String) extends Notificationcaseclass VoiceRecording(contactName: String, link: String) extends NotificationdefshowNotification(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" }}val someSms = SMS("12345", "Are you there?")val someVoiceRecording = VoiceRecording("Tom", "voicerecording.org/id/123")println(showNotification(someSms)) // prints You got an SMS from 12345! Message: Are you there?println(showNotification(someVoiceRecording)) // you received a Voice Recording from Tom! Click the link to hear it: voicerecording.org/id/123
case后面还可以加if语句,我们称之为模式守卫。
defshowImportantNotification(notification: Notification, importantPeopleInfo: Seq[String]): String = { notification match {case Email(sender, _, _) if importantPeopleInfo.contains(sender) =>"You got an email from special someone!"case SMS(number, _) if importantPeopleInfo.contains(number) =>"You got an SMS from special someone!"case other => showNotification(other) // nothing special, delegate to our original showNotification function }}