案例类基础知识
与常规类相比 - 案例类符号提供了几个好处:
-
所有构造函数参数都是
public
,可以在初始化对象上访问(通常情况并非如此,如此处所示):case class Dog1(age: Int) val x = Dog1(18) println(x.age) // 18 (success!) class Dog2(age: Int) val x = new Dog2(18) println(x.age) // Error: "value age is not a member of Dog2"
-
它提供了以下方法的实现:
toString
,equals
,hashCode
(基于属性),copy
,apply
和unapply
:case class Dog(age: Int) val d1 = Dog(10) val d2 = d1.copy(age = 15)
-
它为模式匹配提供了一种方便的机制:
sealed trait Animal // `sealed` modifier allows inheritance within current build-unit only case class Dog(age: Int) extends Animal case class Cat(owner: String) extends Animal val x: Animal = Dog(18) x match { case Dog(x) => println(s"It's a $x years old dog.") case Cat(x) => println(s"This cat belongs to $x.") }