Case class是一种特殊的类,它们经过优化以用来模式匹配。
我们看如下例子
abstract class Personcase class Student(age: Int) extends Personcase class Worker(age: Int,salary:Double) extends Personcase object Shared extends Personobject caseClassObject { def main(args: Array[String]): Unit = { def caseOps(p : Person)= p match { case Student(age) => println("the student age is :"+age) case Worker(_,sal) => println("the Worker's salary is :"+sal) case Shared => println("No perporty!!") } caseOps(Student(10)) caseOps(Worker(25,8000)) caseOps(Shared) }}
运行结果
the student age is :10the Worker's salary is :8000.0No perporty!!
可见使用模式匹配,可以获取创建对象时传入的参数
如果类不是case类,那么上述功能将无法完成。
case class提供了copy方法,可以创建一个与现有对象同值或者不同值的对象
val worker = Worker(36,20000) val worker1 = worker.copy() val worker2 = worker.copy(salary=10000) caseOps(worker2)
worker2的年纪是36,而薪水是10000
这种case class 和case object 特别适用于消息传递系统。