check variable for undefinedness

Rikki Cattermole alphaglosined at gmail.com
Thu Dec 26 03:31:45 PST 2013


On Thursday, 26 December 2013 at 11:03:17 UTC, Dfr wrote:
> Thank you for reply.
>
> Here is what i trying to achieve, i have module-wise data 
> structure, which should exist in form of array and associative 
> array, but i can't calculate second form on compile time:
>
> const a = [["a","1"],["b", "2"], ... ];
> const string[string] b = a.map!(...).assocArray;
>
> This is not allowed, so i trying this approach:
>
> const a = [["a","1"],["b", "2"], ... ];
> const string[string] b;
>
> int some_func() {
>   b = a.map!(...).assocArray;
>   ....
> }
>
> It is ok, but i don't want calculate 'b' every time 'come_func' 
> is called,
> so i'd like to do something like this:
>
> int some_func() {
>   if(b is null) {
>      b = a.map!(...).assocArray;
>   }
>   ....
> }

You are correct in that checking if its null will work.
Another alternative is to check the length of the keys array.

if (b.keys.length == 0) {
     // blah something
}

Are you aware of the static this feature?

static this() {
    if(b is null) {
       b = a.map!(...).assocArray;
    }
}

It runs on init of the module. In other words at the start of the 
application (before main). Although in this case you probably 
don't need to check if its null. As it can be assumed.


More information about the Digitalmars-d-learn mailing list