Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces in Groovy

I'm about to start a social web app project.

While i was designing classes , i decided to define interfaces like "commentable" or "likeable" to use them when needed.

Yet i couldn't figure it out how to implement it in Groovy, that i am in the learning phase.

The Example below is from the Groovy documentation,

 interface X
{ void f(); void g(int n); void h(String s, int n); }

x = [ f: {println "f called"} ] as X
x.f()
//x.g()    // NPE here

Say this is one of my interfaces , and I want to use a Class called B to implement this interface ..

shall I just say B as X , in the related controller?

How to do it in domain layer? If a class Z is, lets say "commentable" , shall i just make a domain class called Comment and say Z hasMany Comment? and use the interface in the controller layer?

What is the Groovy way to do this correctly? I'm bit confused and a little clarification would be really nice.

Thanks in advance

like image 735
add9 Avatar asked Jun 21 '11 13:06

add9


People also ask

What are Groovy properties?

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.

Is Groovy object oriented?

Groovy is a fully fledged object-oriented (OO) language supporting all of the OO programming concepts that are familiar to Java developers: classes, objects, interfaces, inheritance, polymorphism, and others.

How do you make a POJO on Groovy?

To do this, go to the context menu of a table (or several tables) and press Scripted Extension → Generate POJO. groovy. Choose a destination folder, and that's it! The class-file is ready.

What are the data types in Groovy?

Groovy data types can be categorized into simple data types and collective data types. Simple data types include strings, regular expressions (regexes), and numbers. Collective data types include lists, maps, and ranges.


1 Answers

The example you show is not the right one to use when implementing your own interfaces. That's a convenient way to only partially implement an interface. In this example only the f method is implemented, so the others fail as you saw. This is useful for testing when you have a large interface but only call a few methods in the class under test, so you don't need to implement the whole interface.

You implement interfaces in Groovy just like in Java:

interface Math {
   int add(int a, int b)

   int multiply(int a, int b)
}

class SimpleMathImpl implements Math {
   int add(int a, int b) {
      a + b
   }

   int multiply(int a, int b) {
      a * b
   }
}
like image 66
Burt Beckwith Avatar answered Oct 27 '22 16:10

Burt Beckwith