Scala: Does == default to equals?

流过昼夜 提交于 2019-12-05 04:39:14

You are making a very understandable mistake--you are trying to write a type-safe equals (i.e. def equals(r: Rational)) instead of a generic equals (i.e. override def equals(a: Any)).

So instead of overriding equals--note that you don't need the override keyword!--you are creating another method by overloading the type parameters, and then having two equals methods, one which takes Rational and one which takes Any. Same thing with ==; only the Any-parameterized method cannot be overridden.

To get the behavior consistent with Java (and the Scala library), you'd need to rewrite equals as something like

override def equals(a: Any) = a match {
  case r: Rational => numer == r.numer && denom == r.demon
  case _ => false
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!