How does Groovy select method when a user-defined method conflicts with a GDK method -
i wrote following java classes:
package com.example; class myset extends java.util.abstractset { @override public java.util.iterator iterator() { return null; } @override public int size() { return 0; } } interface toset { myset toset(); } public class mylist extends java.util.abstractlist implements toset { @override public object get(int index) { return null; } @override public int size() { return 0; } public myset toset() { return new myset(); } }
and test in groovy:
package com.example class mytest { @org.junit.test public void test() { myset set = new mylist().toset(); println(set.class); println(new mylist().toset().class); def set2 = new mylist().toset(); println(set2.class); } }
the test run results in:
class com.example.myset class java.util.hashset class java.util.hashset
my guess in latter 2 cases expression toset()
invokes gdk's toset
method instead of mylist#toset
, exact rule behavior? groovy's method selection depend not on receiver , arguments, on context?
one more subtle thing if remove implements toset
java code above, test prints class com.example.myset
3 cases. got confused.
in 3 examples mention, toset method never invoked. verified adding print statement toset method in mylist. reason first class printed myset because of assignment variable of type myset - groovy implicitly cast hashset myset upon assignment (magic!).
the rest of behavior more subtle. when no interface implementation declared (you remove implements toset), groovy method dispatcher pick method implementation on mylist class, i.e. method defined. apparently, when interface implementation defined, method dispatcher has choose between interface implementation (mylist toset) , superclass implementation (gdk toset), , it's choosing latter (they both have no arguments).
Comments
Post a Comment