Case Class是样例类,能够被优化以用于模式匹配。
//抽象类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)
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")
}
}
}
//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")
}
}
}
忠于技术,热爱分享。欢迎关注公众号:java大数据编程,了解更多技术内容。