Tuesday, January 13, 2009

Implementing interfaces in Groovy

This a quick post just to put some facts out there after i read this post.

In the post the Vita states that "In Groovy when your class implements a Java interface it must have all the methods present"

Well this is NOT exactly true. Here is an example below of me implementing only the interfaces i want:

This is my very simple interface with 3 methods;

public interface SaySomething {

String saySomethingTrue();

String saySomethingFalse();

String saySomethingFunny();
}


In Groovy you easily implement a multi-method interface with a Map (method name = closure)

So i have code like this. I ONLY implement the methods i want.

SaySomething saySomething = [saySomethingTrue:{'Groovy rocks'},
saySomethingFalse:{'Groovy must implement all methods in a Java interface.'},] as SaySomething;

println "This is true: " + saySomething.saySomethingTrue();

println "This is false: " + saySomething.saySomethingFalse();


As you can see in quick example above i don't provide an implementation for saySomethingFunny()

The result of running this is:

This is true:  Groovy rocks
This is false: Groovy must implement all methods in a Java interface.


UPDATE...

If you just want to do the same thing for all methods:

SaySomething saySomething2 = {return "I am handling all methods"} as SaySomething

println "This is true: " + saySomething2.saySomethingTrue();

println "This is false: " + saySomething2.saySomethingFalse();

println "This is funny: " + saySomething2.saySomethingFunny();


This prints out:

This is true:  I am handling all methods
This is false: I am handling all methods
This is funny: I am handling all methods

5 comments:

chanwit said...

it's true *behind* the scene.

Luke Daley said...

You really should state what happens when you call one of the interface methods that you don't define.

Peter Delahunty said...

Hi Luke

I update the blog entry to show handling all method calls from one closure.

In the case you said. An error would occur if you tried to call a method that does not have and entry in the map.

Anonymous said...

My take on the same problem
http://groovyconsole.appspot.com/script/522001

help with dissertation said...

Not quite time to get acquainted. What he saw impressed.
I liked the section on educational programs on the internet. I would like to know more about programming in HTML.