sachin jain
sachin jain

Reputation: 224

Static Compilation in groovy

I was following the discussion given at: http://docs.codehaus.org/display/GroovyJSR/GEP+10+-+Static+compilation

Code:

    void foo(String msg) { println msg }
    void foo(Object msg) { println 'Object' }

    def doIt = {x ->
      Object o = x
      foo(o)
    }

    def getXXX() { "return String" }

    def o2=getXXX()
    doIt o2   // "String method" or "Object method"????

Now based on the link it should have called the foo method with Object parameter rather than string since the closure works differently than methods as in since the variable passed in the closure is an Object it should invoke the method with Object argument.

But it calls the foo method with String argument.

I am using groovy 2.2.1.


I am new to groovy so got a bit confused how it should work.

In the above example if we want the performance and behavior of the above code to work like it does in Java then we have to use:

@groovy.transform.CompileStatic

This will make sure that the method calling is done during compile tile rather than at run time which enhances the performance of the code.

But if we want to use this then we can not use Closures as this will not compile(as in Java).

So instead of using closures we can use a method.

For testing replace the closure with a method with same logic and it should call the foo method with Object as an argument.

One more thing for someone who is new to groovy when we use @groovy.transform.CompileStatic the performance of the code improves significantly a sin 2-2.5 times.

Upvotes: 1

Views: 1241

Answers (1)

user3155388
user3155388

Reputation: 86

I don't see you using CompileStatic annotation in the above code. If you modify your code into the following then you will see the foo(Object) method getting invoked:

void foo(String msg) { println msg }

void foo(Object msg) { println 'Object' }

@groovy.transform.CompileStatic
def doIt(def x) {
  Object o = x
  foo(o)
}

def getXXX() { "return String" }

def o2=getXXX()
doIt o2   // "String method" or "Object method"????

Upvotes: 2

Related Questions