Groovy will resolve ambiguous method calls by choosing the method with a parameter type that is alphabetically first. In the following example the method that takes a parameter of type "A" will be called if Groovy calls MyClass.printIt(null).
If you refactor this code to rename class A to class C you will find that the call with a null myVariable will then resolve to the method that takes a parameter of type "B", the bottom one.
class MyTest {
public static void main(String[] args) {
B myVariable = new B()
new MyClass().printIt(myVariable)
myVariable = null
new MyClass().printIt(myVariable)
}
}
class A {}
class B {}
class MyClass {
void printIt(A variable) {
println "TOP method called"
}
void printIt(B variable) {
println "BOTTOM method called"
}
}
the code as listed above produces the following output
BOTTOM method called
TOP method called it called the top method with a variable of type B
once class A is renamed to class C the output will change to
BOTTOM method called
BOTTOM method called
try as many permutations as you like, the method that takes the class with the lowest alphabetical name is called when the variable passed in is null, even if the variable is typed for the other class.
groovy --version Groovy Version: 2.0.5 JVM: 1.6.0_33 Vendor: Sun Microsystems Inc. OS: Windows 7
My question is why does Groovy do this, is this by design or is it a bug, is this behavior documented anywhere?
Dave
Can't reproduce this on groovy 2.1.6. Can't reproduce this on groovy 2.0.5 either. In both use cases output is:
BOTTOM method called
TOP method called
When A is renamed to C output is
BOTTOM method called
TOP method called
Gentoo Linux, JDK 1.7.0_25,