简介
Case Class是样例类,能够被优化以用于模式匹配。
- 构造器中的参数如果不被声明为var的话,默认是val类型
- 自动创建伴生对象,实现apply方法,可以不直接显示地new对象
- 伴生对象实现unapply方法,从而可以将case class应用于模式匹配
- 实现toString、hashCode、copy、equals方法
简单实例
``` //抽象类Person abstract class Person
//case class Student case class Student(name:String,age:Int,studentNo:Int) extends Person //case class Teacher case class Teacher(name:String,age:Int,teacherNo:Int) extends Person //case class Nobody case class Nobody(name:String) extends Person
object CaseClassDemo{ def main(args: Array[String]): Unit = { //case class 会自动生成apply方法,从而省去new操作 val p:Person=Student("john",18,1024)
//match case 匹配语法
p match { case Student(name,age,studentNo)=>println(name+":"+age+":"+studentNo) case Teacher(name,age,teacherNo)=>println(name+":"+age+":"+teacherNo) case Nobody(name)=>println(name) } } } ```
常用方法
``` //toString方法演示 scala> val s=Teacher("john",38,1024) s: Teacher = Teacher(john,38,1024)
//无参copy方法演示 scala> val s1=s.copy() s1: Teacher = Teacher(john,38,1024)
//copy方法是深度拷贝 scala> println(s eq s1) false
//equal方法根据对象内容进行比较 scala> println(s equals s1) true
scala> println(s == s1) true
//hashcode方法 scala> s1.hashCode res45: Int = 567742485
//toString方法 scala> s1.toString res46: String = Teacher(john,38,1024)
//带一个参数的copy方法 scala> s1.copy(name="stephen") res47: Teacher = Teacher(stephen,38,1024) //带二个参数的copy方法 scala> s1.copy(name="stephen",age=58) res49: Teacher = Teacher(stephen,58,1024) //带三个参数的copy方法 scala> s1.copy(name="stephen",age=58,teacherNo=2015) res50: Teacher = Teacher(stephen,58,2015) ```
多参数的Case Class
``` abstract class Person
case class Student( name:String, age:Int, studentNo:Int) extends Person
case class Teacher( name:String, age:Int, teacherNo:Int) extends Person
case class Nobody( name:String) extends Person
//SchoolClass为接受多个Person类型参数的类 case class SchoolClass(classDescription:String,persons:Person*)
//下列代码给出的是其模式匹配应用示例 object CaseClassDemo{ def main(args: Array[String]): Unit = { val sc=SchoolClass("学途无忧网Scala培训班",Teacher("摇摆少年梦",27,2015),Student("摇摆少年梦",27,2015)) sc match{ case SchoolClass(,,Student(name,age,studetNo))=>println(name) case _ => println("Nobody") } } } ```
sealed case class
sealed关键字作用
- 其修饰的trait,class只能在当前文件里面被继承
- 用sealed修饰的目的是告诉scala编译器在检查模式匹配时,让scala能在编译时检查代码是否有漏掉什么没case到的代码,减少编程的错误。
简单实例
``` //Person最前面加了个关键字sealed sealed abstract class Person
case class Student( name:String, age:Int, studentNo:Int) extends Person
case class Teacher( name:String, age:Int, teacherNo:Int) extends Person
case class Nobody( name:String) extends Person
case class SchoolClass(classDescription:String,persons:Person*)
object CaseClassDemo{ def main(args: Array[String]): Unit = { val s:Person=Student("john",18,1024) //这边仅仅给出了匹配Student的情况,在编译时 //编译器会提示 //match may not be exhaustive. It would fail on the following inputs: Nobody(), Teacher(, _, _) s match{ case Student(name,age,studentNo)=>println("Student") } } } ```
文章来自:https://www.itjmd.com/news/show-4236.html