ᴘᴀɴᴀʏɪᴏᴛɪs ᴘᴀɴᴀʏɪᴏᴛɪs - 2 months ago 9
Groovy Question

Does Groovy auto-box boolean to Object by default?

Consider this Java class:

public class Demo {

public void a(boolean a){
System.out.println("boolean was called");
}

public void a(Object a){
System.out.println("Object was called");
}

}


Groovy class:

class Groovy {
static void main(String[] args) {
def demo = new Demo()
demo.a(true)
}
}


Output:

Object was called


Writing a test for it in Groovy and passing in a primitive
true
calls
a(Object)
instead.

Is this intended behaviour and how can I call the other method? (I'm on version 2.4.6)

FYI this causes problems with EasyMock (#175890293)

Answer

Groovy autowraps primitives, so it is intended behaviour.

Also due to the autowrapping, the method resolution is different from Java, which causes your issue:

http://docs.groovy-lang.org/latest/html/documentation/core-differences-java.html#_primitives_and_wrappers

The solution for your problem is to cast your "true" constant to a boolean primitive in the method call.

class Groovy {
    static void main(String[] args) {
        def demo = new Demo()
        demo.a((boolean) true)
    }
}

This prints "boolean was called".

Comments