匹配对象及样例类

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) {
23       None
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)

 

posted @ 2022-05-24 20:59  小王同学学编程  阅读(95)  评论(0编辑  收藏  举报
levels of contents