快学Scala 第十三课 (类型层级,对象相等性)

Scala 类型层级:

对象相等性:

和Java一样要重写equals方法和hashcode方法

class Student(val id: Int, val name: String) {
  override def equals(other: Any) = {
    val that = other.asInstanceOf[Student]
    if (that == null) false
    else id == that.id && name == that.name
  }

  override def hashCode = 13 * id.hashCode() + 17 * name.hashCode()

}


object TestCase {
    def main(args: Array[String]): Unit = {
    
      val s1 = new Student(1,"Sky")
      val s2 = new Student(1,"Sky")
      
      println(s1.equals(s2))
      println(s1 == (s2))
  
  }
  
}

返回结果:

true

true

原文地址:https://www.cnblogs.com/AK47Sonic/p/7352474.html