Michael H
Michael H

Reputation: 43

Overload == in Groovy to not return boolean

I'm currently developing a DSL using Groovy for a math related API written in Java.

The Expression class has a method with the following signature:

public Constraint equals(Expression that)

We want to define a constraint, which will only be evaluated later.

Is it possible to override == using our equals implementation so that it doesn't return boolean but Constraint?

Upvotes: 3

Views: 210

Answers (1)

tim_yates
tim_yates

Reputation: 171084

No, as far as I know, it is not possible...

The == operator at some point ends up in DefaultTypeTransformation.java::compareEqual which returns boolean, so even if you do:

class Yay {}

class Woo {
    String equals(Yay y) {
        'hello'
    }
}

println new Woo() == new Yay()

You will get the exception:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.compareEqual(DefaultTypeTransformation.java:641)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareEqual(ScriptBytecodeAdapter.java:684)
    at ConsoleScript3.run(ConsoleScript3:9)

It will work with a.equals(b), but not a == b

Upvotes: 4

Related Questions