sriram
sriram

Reputation: 9032

How does Groovy work in a dynamic way?

I have built a small compiler, for a statically typed language. After understanding how a static language works, I'm having trouble getting my head into dynamic languages like groovy.

While constructing my compiler, I know that once I generate the machine level-code there is no way of changing it! (i.e its run-time).

But how does Groovy do this magical stuff like inferring type in statements like:

def a = "string"
a.size()

As far as I'm concerned, groovy has to find the type a is of string before running the line a.size(). It seems that it does so in compile time (while constructing AST)! But the language is called dynamic.

I'm confused, kindly help me figure out.

Thanks.

Upvotes: 2

Views: 2189

Answers (1)

Will
Will

Reputation: 14519

Groovy doesn't simply "call" a method, but dispatches it through the meta-object protocol. The method invocation is sent as a message to the object, which can respond to it or not. When using dynamic typing, it doesn't matter the object type, only if it responds to that message. This is called duck typing.

You can see it (though not easily) when you decompile Groovy code. You can compile using groovyc and decompile using other tool. I recommend jd-gui. You won't see the method being called explicitly, because of Groovy's method caching (it is done this way to achieve Groovy's neat performance).

For a simple script like:

def a = "abcdefg"
println a.substring(2)

This will be the generated code:

CallSite[] arrayOfCallSite = $getCallSiteArray(); Object a = "abcdefg";
return arrayOfCallSite[1].callCurrent(
    this, arrayOfCallSite[2].call(a, Integer.valueOf(2))); return null;

And the method call is "dispatched" to the object, not called directly. This is a similar concept to Smalltalks and Ruby method dispatch. It is because of that mechanism that you can intercept methods and property access on Groovy objects.

Since Groovy 2, Groovy code can be statically compiled, thus acting like your compiler.

Upvotes: 5

Related Questions