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

DeegC picture DeegC · Jun 18, 2015 · Viewed 7.5k times · Source

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.

Answer

Gregor Ra&#253;man picture Gregor Raýman · Jun 18, 2015

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.