Re: [Vala] How to initialize static field




I want to create some static fields. Int field works ok, but HashMap
remains null even after initialization... What i did wrong?
You didn't run the initialization. The static constructor only runs when
the corresponding metaobject is requested for the first time. It is only
requested when you create instance, call "class" methods, access "class"
members or use typeof on the type. It is however NOT requested when you
use "static" methods and members.

Thanks! I couldn't find anything about such behaviour in documentation :(

But i still don't understand how to initialize it properly:
public static class Foo: Object {
      public static HashMap<string, int>  bar = new HashMap<string, int>();
This is only executed when you obtain the class object.

If the member was a class one rather than static one, i.e.

        public class HashMap<string, int>  bar = new HashMap<string, int>();

the initialization would be enforced when accessing it (at the cost of the
access being slightly slower).

public static class Foo: Object {
public class HashMap<string, int> bar = new HashMap<string, int>();
public static int a = 5;
}

void main () {
stdout.printf("a = %d\n",Foo.a);
stdout.printf("bar: %s\n",(Foo.bar==null?"null":"ok"));
}

Failed to compile:

$ valac --pkg=gee-1.0 t1.vala --pkg=vala-1.0

** (valac:29753): CRITICAL **: vala_ccode_function_call_add_argument: assertion `expr != NULL' failed
/home/pavels/Projects/vala_test/t1/t1.vala.c: In function ‘_main’:
/home/pavels/Projects/vala_test/t1/t1.vala.c:94: error: expected expression before ‘)’ token
error: cc exited with status 256
Compilation failed: 1 error(s), 0 warning(s)

void main () {
To enforce initialization of static members of Foo, you can try putting
        typeof(Foo);
here.


Didn't help either:

using Gee;

public static class Foo: Object {
public static HashMap<string, int> bar = new HashMap<string, int>();
public static int a = 5;
}

void main () {
typeof(Foo);
stdout.printf("a = %d\n",Foo.a);
stdout.printf("bar: %s\n",(Foo.bar==null?"null":"ok"));
}

prints

a = 5
bar: null



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]