1

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.

K J
  • 4,505
  • 6
  • 27
  • 45
  • First part IMO is also not easy: `equals` has signature `equals(x: Any): Boolean` and `T` is erased. – Victor Moroz Sep 04 '16 at 02:36
  • 1
    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 Sep 04 '16 at 03:14

1 Answers1

2

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
Victor Moroz
  • 9,167
  • 1
  • 19
  • 23