Reputation: 18289
I am asking "why is this possible in Groovy?" for the following two code blocks. Maybe I should have created two separate questions, but these seem closely related.
First,
class Dog
{
public speak() {
return "Bark"
}
}
Notice how speak()
doesn't have a return type, and I didn't say def
. Yet, the code works as if I included def
.
Second,
@interface MyAnnotation {
}
interface Canine{
@MyAnnotation
speak()
}
Notice how the speak()
method doesn't have a return type, but it works when I put an annotation on the method.
Why do both of these code blocks work (i.e., no errors when I use them)? Why does the first one work iff I put public
before it, and why does the second one work iff I put an annotation on it? And where is this documented?
EDIT:
Here is a runnable script that demonstrates both oddities:
@interface MyAnnotation { }
interface Canine{
@MyAnnotation
speak()
}
class Dog implements Canine
{
public speak() {
return "Bark"
}
}
Dog fido = new Dog()
println fido.speak()
Upvotes: 2
Views: 1065
Reputation: 96424
Groovy is designed to be flexible and permissive. As long as you use either def, a return type, public, or an annotation, and you have ()
at the end (and the name doesn't match the enclosing class), the interpreter figures out that it's a method declaration and it lets you do it. If you don't care about the return type enough to indicate it, Groovy is also fine with not caring about it. That's the design philosophy.
This syntax isn't documented anywhere I can find. I would guess that indicates this syntax is subject to change. I would hesitate to rely on this and would stick to using def or a return type, if only for the sake of clarity.
Upvotes: 3