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.

2
  • First part IMO is also not easy: equals has signature equals(x: Any): Boolean and T is erased. Commented Sep 4, 2016 at 2: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. Commented Sep 4, 2016 at 3:14

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.