Use the Trait, but has error

the code is following.
when i use Trait, and in the class Point4 to write the isEqual method, but the isEqual has error,
the error is “incompatible type in overriding”
trait Equal{
def isEqual(x:Any): Boolean
def isNotEqual(x:Any): Boolean = !isEqual(x)
}
class Point4(xc:Int, yc:Int) extends Equal{
var x:Int = xc
var y:Int = yc
def isEqual(obj:Any): Unit ={
obj.isInstanceOf[Point4] && obj.asInstanceOf[Point4].x == x
}
}
object useEqual{
def main(args: Array[String]): Unit = {
val p1 = new Point4(2, 3)
val p2 = new Point4(2, 4)
val p3 = new Point(3, 3)
println(p1.isNotEqual(p2))
println(p1.isNotEqual(p3))
println(p1.isEqual(p3))
}
}

In the class point, you should say (replacing Unit by Boolean)

def isEqual(obj:Any): Boolean ={
obj.isInstanceOf[Point4] && obj.asInstanceOf[Point4].x == x
}

regards,
Siddhartha

1 Like

thank you, use the Boolean to rewrite the Unit, the error is disappear.

Note that it’s more idiomatic and less error-prone to use pattern matching rather than isInstanceOf and asInstanceOf:

def isEqual(obj: Any): Boolean = obj match {
  case p: Point4 => p.x == x
  case _ => false
}
1 Like

I don’t have enough context to know where to start and stop giving you advice. So, here’s a high-level overview.

  1. Don’t implement any form of equals, either overriding equals from java.lang.Object or from your own base trait
    • This is a deeply treacherous space which you are almost certainly going to get incorrect in subtle ways
    • Surprise, you almost certainly must also override and implement a sister method, hashCode
  2. Find FP idiomatic ways (Equals type-class) to derive and exploit any form of equivalence

If you just MUST override java.lang.Object.equals(), then read and re-read this StackOverflow Question and Answer addressing the area until you are sure you understand it.

Once you think you understand it (you don’t yet…the understanding comes from the pain of thinking you do and then iterating many times to fill in all the subtle corner cases), create your own implementation.

And then find another Scala expert set of eyes to validate it. The odds you will get it right the first time are essentially zero. And the ways you can get it wrong will likely not be discovered until at runtime. In production. When you least want it to happen. Like just after a deployment.

Again, I cannot emphasize enough to heed items 1 and 2 above. Many MANY hours lost here for me in my education in this area.

2 Likes