Refer to the following code snippet:
trait Fruit {
val color:String
def == (fruit:Fruit) = this.color == fruit.color
}
case class Orange(color:String) extends Fruit
case class Apple(color:String) extends Fruit
As expected, Orange("red") == Orange("red") is true. However, I would like to enforce that only the same type of fruits can be compared, so for instance Orange("red") == Apple("red") should give an error. Can we enforce this in the signature of == in trait Fruit in an elegant way?
EDIT: I want the error to be caught at compile time, not at runtime.
Scalaz has an Equal “type class” that solves this problem, albeit with a different operator.
https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Equal.scala
The heart of it is basically this (although I use === where they use some unicode)
And is used like so