Groovy class use another instance field

Serban Cezar :

I am trying to build a Groovy class with properties and have one property depend on one another. But I always seem to get a null or default value. I tried using the 'this' keyword but I am missing something fundamental. I know it probably has something to do with instance variables.

Say I have the following:

class BaseClass {
    String jobName
    String jobDescription = jobName + '-description'
}

If I instantiate the class and declare both attributes, everything works:

new BaseClass().with {
        jobName = 'test-job'
        jobDescription = 'Sample description'
    }

But if I only instantiate the jobName property, the description uses null. So it will be 'null-description'.

Is there any way I can instantiate an object and use the jobName property so I don' have to repeat myself for every object I create?

cfrick :

I think you are best off with overriding the setter for jobName and then defensively set the description. E.g.

class BaseClass {

    String jobName

    String jobDescription

    void setJobName(String jobName) {
        this.jobName = jobName
        if (!jobDescription) {
            jobDescription = "${jobName}-description"
        }
    }
}

assert new BaseClass().tap{ jobName = 'test-job' }.jobDescription == 'test-job-description'

The reason your attempt does not work as expected is due to the flow of things happening - the attribute default is done at construction time of the object. So setting the job later (inside the with) has no effect (it will not be calculated again from the new input).

Another option would be an constructor based approach (e.g. use final and deal with this problem in the c'tor to create a default description)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=292255&siteId=1