匹配物件及樣例類
阿新 • • 發佈:2022-05-24
1、匹配物件
1 object Test4_MatchObject { 2 def main(args: Array[String]): Unit = { 3 val student = new Student("wl", 22) 4 5 //針對物件例項的內容進行匹配 6 val result = student match { 7 case Student("wl", 22) => "wl 22" 8 case _ => "exit!" 9 } 10 println(result) 11 }12 } 13 14 //定義類 15 class Student(val name: String, val age: Int) 16 17 //定義伴生物件 18 object Student { 19 def apply (name: String, age: Int): Student = new Student(name, age) 20 // 必須實現一個unapply方法,用來對物件屬性進行拆解 21 def unapply(student: Student): Option[(String, Int)] = { 22 if (student == null) { 23None 24 } else { 25 Some(student.name, student.age) 26 } 27 } 28 }
2、匹配樣例類,是物件匹配的簡單使用
1 object Test5_MatchCaseClass { 2 def main(args: Array[String]): Unit = { 3 val student1 = new Student1("wl", 22) 4 5 //針對物件例項的內容進行匹配 6 val result = student1 match {7 case Student1("wl", 22) => "wl 22" 8 case _ => "exit!" 9 } 10 println(result) 11 } 12 } 13 14 //定義樣例類, 是物件匹配的簡單使用 15 case class Student1(name: String, val age: Int)