1
votes

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.

1
First part IMO is also not easy: equals has signature equals(x: Any): Boolean and T is erased.Victor Moroz
Do you really need ==? It's easy to define a standalone method in both directions, or define another method implicitly. You can't really override == in Int as it's already there.Victor Moroz

1 Answers

2
votes

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