Scala: Is there any way to override "not equals" (!=)?

10k views Asked by At

I'm writing a DSL that generates SQL. The syntax for loading a table is:

    session.activateWhere( _.User.ID == 490 )

This will select from the User table where the ID column is 490. I can use "==" because I can override "equals()" to generate the correct SQL. My problem is that "!=" doesn't work because it calls equals() and then negates the result. Sadly "!=" is final so I can't override it. Is there any way in my equals() method to tell that it was called as part of !=?

I've implemented a "<>" operation that logically does the same thing as "!=" and it works fine:

    session.activateWhere( _.User.ID <> 490 )

My issue is that not only is "!=" valid syntax (to the compiler) but it will run and generate the exact opposite of what the user intends.

2

There are 2 answers

1
Gregor Raýman On

As you say, != is (similarly to ==) final and so cannot be overridden - with a very good reason. That is why most DLSs use === as an alternative.

The == and != operators have a very well defines meaning for all objects in Scala. Changing the meaning for some objects would be, in my opinion, very dangerous.

0
volia17 On

If you want to use == and !=, you have to override equals, hashcode and canEqual (trait Equals)

It is not a simple as it looks, you have to be carreful.

There is some examples over the net. For example : https://www.safaribooksonline.com/library/view/scala-cookbook/9781449340292/ch04s16.html

Another one : https://groups.google.com/forum/#!msg/scala-user/Qosfawmaecw/RUWigwvVtQ4J