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:

int a = "20" as int
assert a==20

The ‘as’ operator can be used to provide implementation to interface as well. Here is an example of the same:

interface Eatable{
   void eat()
}

def x =  {println "It's groovy style" } as Eatable
x.eat()

Had it been java, this could have been achieved through an annonymous class like this:

new Eatable(){
  void eat(){
    System.out.println "Its java style"
  }
}.eat() 
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 comment -