Matt Westlake
Matt Westlake

Reputation: 3651

Grails initialization of classes

I have a question about initialization wiith groovy/grails. When I have the following class, sInstance doesn't get passed into the SService initialization.

class A {

    String sInstance
    String app
    String dbInstance

    SService s = new SService(sInstance:sInstance, app:app)
}

SService class:

class SService {

    String sInstance
    String app

public getSInstance{
    return sInstance
    }
}

This returns null, where

class A {

    String sInstance
    String app
    String dbInstance

public initializeSService{
    SService s = new SService(sInstance:sInstance, app:app)
    }
}

returns the sInstance variable from the SService class.

Why is that and how can I have SService object initialized with the class A constructor?

Upvotes: 0

Views: 288

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

You can't do something like this:

class A {

    String sInstance
    String app
    String dbInstance

    SService s = new SService(sInstance:sInstance, app:app)
}

The problem with that is when you are creating an instance of SService, sInstance has not been initialized yet. If you want to pass sInstance to a constructor of some other class from within the A class, you are going to have to do it after sInstance has been assigned a value, like a method that is called after A is fully constructed.

EDIT:

Trying to clarify something from the comments below:

class A {
    String sInstance
    String app
    String dbInstance

    void anyMethod() {
        // this will work as long as you have initialized sInstance
        SService s = new SService(sInstance:sInstance, app:app)
    }
}

Depending on what you are really trying to do, maybe something in this direction:

class A {
    String sInstance
    String app
    String dbInstance
    SService s

    void initializeS() {
        if(s == null) {
            // this will work as long as you have initialized sInstance
            s = new SService(sInstance:sInstance, app:app)
        }
    }
}

Or:

class A {
    String sInstance
    String app
    String dbInstance
    SService theService

    SService getTheService() {
        if(theService == null) {
            // this will work as long as you have initialized sInstance
            theService = new SService(sInstance:sInstance, app:app)
        }
        theService
    }

    def someMethodWhichUsesTheService() {
        getTheService().doSomethingToIt()
    }
}

Upvotes: 2

Related Questions