Closure as an implementation to interface

04 / Oct / 2011 by Mohd Farid 2 comments

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]

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Erik Pragt

    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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *