Constructor vs InitVars

20 views
Skip to first unread message

Kaya TC

unread,
May 30, 2016, 5:32:29 AM5/30/16
to CodenameOne Discussions
Hey guys,

i had a problem that my initialized Variables where "null", and according to this commentary in the source


        // do not modify, write code in initVars and initialize class members
        // there, the constructor might be invoked too late due to race
        // conditions that might occur

i should use the initVars method, which i did but i got null for the values, now after an hour of testing different approaches like beforeShow/postShow/googleing without a success i decided to put t in the constructor and it works as i wanted it to.

So did i get the sentence wrong and should have used the constructor instead of initVars?
but what about the javadoc right on the bottom of the constructor?


    /**
     * this method should be used to initialize variables instead of the
     * constructor/class scope to avoid race conditions
     */


im hella confused now

Regards

Shai Almog

unread,
May 31, 2016, 12:06:23 AM5/31/16
to CodenameOne Discussions
Hi,
it is confusing. I'm guessing your code looked like this:

private Object myVar = null;

initVars() {
    myVar = new ...;
}

Then you were surprised that myVar is null because the null assignment happens AFTER the new statement!

Kaya TC

unread,
May 31, 2016, 2:38:09 AM5/31/16
to CodenameOne Discussions
Hi Shai,

my variable is already initialized at declaration in that special case, but yes you are right in the point that the whole stuff gets initiliazed very late.

So then my approach now will be to initialize that part in the initVars and run the methods from there.
Reply all
Reply to author
Forward
0 new messages