scala 模式匹配与case class

时间:2022-10-29 05:52:06

当一个类被声明为case class时,编译器会自动进行如下操作:

1.构造器中参数如果没有被声明为var,则默认为val类型;

2.自动创建伴生对象,同时在伴生对象中实现apply方法,这样在使用时就不用显式地使用new对象;

3.伴生对象中同样可以实现unapply(),从而可以将case class应用于模式匹配;

object Test {

case class Student(name:String,age:Int,stuentNo:Int) extends Person(name)

case class Teacher(name:String,age:Int,teacherNo:Int) extends Person(name)

case class Nobody(name:String) extends Person(name)

def main(args: Array[String]): Unit = {

//case class 会自动生成apply方法,从而省去了new
val p:Person = Student("sb",18,1024)

p match {
case Student(name,age,stuentNo) => println(name + ":" + age + ":" + stuentNo)
case Teacher(name,age,teacherNo) => println(name + ":" + age + ":" + teacherNo)
case Nobody(name) => println(name)
}

}
}

abstract class Person(name:String)