案例類基礎知識

與常規類相比 - 案例類符號提供了幾個好處:

  • 所有建構函式引數都是 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"
    
  • 它提供了以下方法的實現:toStringequalshashCode(基於屬性),copyapplyunapply

    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.")
    }