Closure as an implementation to interface
Recently, I saw some code of grails Hibernate Plugin and noticed an interesting usage of ‘as’ operator. The ‘as’ operator of groovy is typically used to change the types of objects.
For example:
[groovy]
int a = "20" as int
assert a==20
[/groovy]
The ‘as’ operator can be used to provide implementation to interface as well. Here is an example of the same:
[groovy]
interface Eatable{
void eat()
}
def x = {println "It’s groovy style" } as Eatable
x.eat()
[/groovy]
Had it been java, this could have been achieved through an annonymous class like this:
[java]
new Eatable(){
void eat(){
System.out.println "Its java style"
}
}.eat()
[/java]
Thanks Erik.
Hi Mohd,
Please check out this page on the Groovy website about multiple ways to implement interfaces:
It provides a bit more information, and also shows you how to use maps to implement interfaces.
Kind regards, Erik Pragt