Tuesday, June 23, 2009

Groovy Dynamic Typing

Groovy Dynamic Beahaviour.

As oposed to Java, Groovy is dynamically typed. Which basically means that the type is not checked at compile time, but instead only at runtime.
Besides some drawbacks, this allows to do many cool things including Duck Typing.
The principle of duck typing is that "if it quacks like a duck it's a duck". this basically means that the behaviour of the Object is based on the use it has on the application, not on its specific type.
In essence this allows to call an object's methods without knowing (at compile time) that these methods exist. In Runtime the methods are invoked. Note that this works even with two different unrelated (No hierarchy or interfaces shared) objects, that implements the method, and precisely this is the beauty of it.

For example

[CODE]
def metodo(anything){
anything.call(144)
}

metodo{
println it
}

def clos2= {println it+it}
metodo(clos2)

class X{
public def call(value){
println value*3
}
}

metodo(new X())
[/CODE]

As you can see, the method "metodo" is called three times with different types.
The first two times is called with a Closure, one inline closure and other declared closure.
And the third time with a totally different object X. That happens to implement the methdo in its own way.

No comments: