import scala.util.Random //做一个信息的识别 abstract class Notificatition //定义不同信息的样例类 case class Email(sender: String, title: String, body: String) extends Notificatition case class SMS(caller: String, msg: String) extends Notificatition case class VoiceRecording(contactName: String, link: String) extends Notificatition object PatternDemo2 { def showNotificatition(notificatition: Notificatition): String = { notificatition match { case Email(sender, title, body) => "收到邮件" + sender case SMS(caller, msg) => "收到SMS" + caller case VoiceRecording(contactName, link) => "收到录音" + contactName case _ => "获取到垃圾信息" } } def main(args: Array[String]): Unit = { val email = Email("zhangsan", "lisi", "hhhh") val email2 = Email("lisi", "lisi", "hhhh") println(showNotificatition(email)) println(showNotificatition(email2)) //类型匹配 val arr = Array("s", 1, 'c') val obj = arr(Random.nextInt(3)) println(obj) obj match { case x: Int => println(x) case s: String => println(s.toUpperCase) case c: Char => println(c) case _ => println("fail") } } } |