Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: constructor issue

Tags:

groovy

If I have a class like this:

class Person { 
def name
def greeting = "hello $name"
}

and I call bob = new Person(name: "bob")

when I inspect Bob at this point i see that the greeting does not have 'bob' in it. What am I doing wrong?

like image 722
dbrin Avatar asked Jul 18 '11 07:07

dbrin


People also ask

What is Groovy constructor?

Groovy adds the constructor automatically in the generated class. We can use named arguments to create an instance of a POGO, because of the Map argument constructor. This only works if we don't add our own constructor and the properties are not final. Since Groovy 2.5.

Can a constructor be private static final return type can be there?

No, a constructor can't be made final. A final method cannot be overridden by any subclasses.

What is MetaClass in Groovy?

A MetaClass within Groovy defines the behaviour of any given Groovy or Java class. The MetaClass interface defines two parts. The client API, which is defined via the extend MetaObjectProtocol interface and the contract with the Groovy runtime system.

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!


1 Answers

You can use the @Lazy annotation to get round this issue

class Person { 
  def name
  @Lazy def greeting = "hello $name"
}

bob = new Person(name: "bob")
println bob.greeting

Will print hello bob as you require. The annotation alters the getter for greeting so that it is only generated the first time it is called (and then the result is cached). This has the side effect of making greeting static once it has been called once, but you don't say whether it is required to change (due to name changing) over time... ie;

bob = new Person(name: "bob")
println bob.greeting
bob.name = 'dave'
println bob.greeting

Will print:

hello bob
hello bob
like image 191
tim_yates Avatar answered Sep 30 '22 17:09

tim_yates