case class

20 阅读1分钟

case class

1.是 Scala 中一种特殊的类,它用于创建不可变的数据容器。

2.case class 创建的对象是不可变的,一旦创建,其属性值不能被修改

3.普通的class 在实例化时,必须要写new的。

4.自动重写方法: toString, equals, hashCode, copy。

eg:

package caseclass

object caseclass {
  case class Student(var id: String, var name: String) {
    override def equals(obj: Any): Boolean = {
      val other = obj.asInstanceOf[Student]
      other.id == id && other.name == name
    }

    override def toString: String = {
      s"Student(${id}, ${name})"
    }

  }

  def main(args: Array[String]): Unit = {

    val stu1 = new Student("1", "小花")
    val stu2 = new Student("1", "小花")
    println(stu1)

    println(stu1 == stu2)

    val set = Set(stu1, stu2)
    //val set1 = Set(1,2,3,1,1,1)
    println(set1) //?
  }
}

case class(样例类)

v.s. class(类)

1.case class 可以在定义对象时,省略new

2.case class 的属性在默认的情况下时是只读的。如果希望可以修改,那需要主动使用var

3.case class 会自动重写 equals, toString.....

当我们只需要使用类来表示数据的时候,就可以选择使用case class,他更加简单

eg:

object caseclass01 {
  case class Student(var id: String, var name: String) {

  }
      class Student2(var id:String, var name:Student) {

      }

  def main(args: Array[String]): Unit = {
    val stu1 = new Student("1", "小花")
    val stu2 = new Student("1", "小花")
    println(stu1 == stu2)

    println(stu1)
    println(Student("1","小花"))
    //stu1.name = "小花花"
    //val stu2 = new Student2("1","小花")
  }
}