本文主要是介绍scala 模式匹配与case class,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当一个类被声明为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)
这篇关于scala 模式匹配与case class的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!