-
equals比较的是值是否相等
-
eq比较的是 地址是否相等
-
==,如果比较的对象是null,==调用的是eq方法,如果比较的对象不是null,==调用的是equals方法
object ObjectEqualsOps { def main(args: Array[String]): Unit = { val kp = new Worker("KP", 30) val kp2 = new Worker("KP", 30) println(kp.equals(kp2)) //true println(kp.eq(kp2)) //false println(kp == kp2) //true var a = null var b = null println(a.eq(b)) //true } } class Worker { var name: String = _ var age: Int = _ def this(name: String, age: Int) = { this() this.name = name this.age = age } override def equals(obj: Any): Boolean = { if (obj == null) { return false } else if (!obj.isInstanceOf[Worker]) { return false } else { //强制转换 var that = obj.asInstanceOf[Worker] this.name.equals(that.name) && this.age== that.age } } }
使用模式匹配重写 equals方法
override def equals(obj: Any): Boolean = {
obj match {
case that:Worker =>{
this.name.equals(that.name) && this.age == that.age
}
case _ =>{
false
}
}