class GroovyClass {
def aVariable
void setAVariable(aVariable)
{
this.aVariable = aVariable;
}
}
My understanding was that we don’t need to specify the type of a variable in a groovy class. But Groovy compiler complains if I declare ‘aVariable’ , why isn’t it considered as a typeless variable with default accessibility ? Should every variable be defined with a def in Groovy both local and class ? Why is it that the function definition doesn’t have to begin with a def ? and when I’m passing in a variable to the setter, it doesn’t need any def in there ?
That code works fine. What do you mean by “Groovy compiler complains”?
You can define that function with a
defif you wanted, and it would returnaVariable(as that is what the assignment operatop returns), however, it wouldnt be following the standard for Java Beans in that setters should return nullGiven that however, I can run:
And it works fine
Edit
Basically, it’s all down to the Groovy parser. The parser expects some sort of list of 1..N keywords defining it’s type or visibility, and then a name for the variable. So the following are all valid:
But you cannot just (with the current parser) say:
Thinking about it, there’s no reason I can currently think of for this restriction (as you can declare vars without
defin Groovy), but the restriction is there, so you need to typedefwhen defining class attributes.