Reputation: 4743
I've defined a wrapper class:
class Wrapper[T](private val value: T)
and I want to make sure that w(v1) == v2 and v2 == w(v1) iff v1 == v2. The first part is easy because you can override equals method of Wrapper class. But the problem is the other way around, making 5 == Wrapper(5) return true for example, achieving symmetry of equality. Is it possible in scala that you can override equals method of basic types like Int or String? In C++, you can override both operator==(A, int) and operator==(int, A) but it doesn't seem so with java or scala.
Upvotes: 1
Views: 164
Reputation: 9225
How it can possibly be done with implicits (note that neither ==
nor equals
can be used here):
import scala.reflect.ClassTag
implicit class Wrapper[T : ClassTag](val value: T) {
def isEqual(other: Any) = other match {
case x: T =>
x == value
case x: Wrapper[T] =>
x.value == value
case _ =>
false
}
}
5 isEqual (new Wrapper(5)) // true
(new Wrapper(5)) isEqual 5 // true
Upvotes: 2