覆盖AnyRef类中的equals方法无法正常工作

时间:2017-03-18 01:35:07

标签: scala

我试图看看是否可以在Car(AnyRef)类中覆盖equals方法。它不起作用。有人可以指出equals方法中的错误吗?

class Car(name:String, price:Float) {

  override def equals(that:Any):Boolean = {
    val thatCar = that.asInstanceOf[Car]
    name == thatCar.name
  }
}
val aCar1 = new Car("Honda", 1000)
val aCar2 = new Car("Honda", 1000)
aCar1==aCar2

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的。

<track kind="captions" src="data:text/vtt;base64,MYBASE64ENCODEDBYTES... "/>

请注意,您无法访问class Car(val name:String, val price:Float){ override def equals(that:Any):Boolean = that match { case x: Car => name == x.name case _ => false } } val aCar1 = new Car("Honda", 1000) val aCar2 = new Car("Honda", 2100) val aCar3 = new Car("Dodge", 3300) aCar1==aCar2 // res0: Boolean = true aCar1==aCar3 // res1: Boolean = false aCar1=="Honda" // res2: Boolean = false 构造函数参数,除非它被声明为Car.name,否则它对实例是私有的。

答案 1 :(得分:0)

@jwvh已经给出了一个很好的答案。只是想补充一点,你也可以使用case class

case class Car(name: String, price: Float) {
  override def equals(that: Any): Boolean = that match {
    case x: Car => name == x.name
    case _ => false
  }
}

val car1 = Car("Honda", 8000)
val car2 = Car("Audi", 9000)
val car3 = Car("Honda", 7500)

car1 == car2  // false
car1 == car3  // true