0

I see that the comparison operator (otherwise method) (==) is defined in the Any class in Scala as final (similarly != operator as well). Any is the universal super class in Scala.

final def ==(that: Any): Boolean

This means that the method (==) can not be overridden in any of the sub classes. IF this is the case, how when we compare two integers / strings, the result is always correct ?

I tried in Scala's REPL.

E.g: 1==1 returns true.

user3103957
  • 636
  • 4
  • 16
  • 6
    You override `equals`. See [What's the difference between == and .equals in Scala?](https://stackoverflow.com/questions/7681161/whats-the-difference-between-and-equals-in-scala) – Panda May 27 '19 at 04:19
  • 4
    As @Panda just said, you can override `equals`. Basically, `==` _(as the [documentation](https://www.scala-lang.org/api/current/scala/Any.html#==(x$1:Any):Boolean) said)_ just forwards to `equals` _(you can confirm that on the [source](https://github.com/scala/scala/blob/2.13.x/src/library-aux/scala/Any.scala#L92))_. - Why `==` exists and why it is final. First because `1 == 1` seems more _"nice"_ than `1.equals(1)`. Second, it makes sense that `==` will always forward to `equals`, thus allowing to override it may lead to strange problems. – Luis Miguel Mejía Suárez May 27 '19 at 04:23
  • That opened my eye! Thanks to both of you! – user3103957 May 27 '19 at 04:57
  • 3
    Possible duplicate of [What's the difference between == and .equals in Scala?](https://stackoverflow.com/questions/7681161/whats-the-difference-between-and-equals-in-scala) – Suma May 27 '19 at 06:11
  • `def ==(that: Any): Boolean` is not the same thing as `def ==(that: Int): Boolean`, which is what `1 == 1` calls. – jwvh May 27 '19 at 09:35

0 Answers0