Re: [Vala] static string variable is empty!



golnaz nilieh wrote:
Hello everybody!
I'm a newbie to vala language, I faced to a strange problem recently and
couldn't find any help in vala documentations.
In my app, I have declared a class named "Global" in a file "global.vala":

using GLib;
public class MyApp.Global : GLib.Object {
    public static string dataDir = "/usr/local/share/";
}

And I have a "main.vala" file, whith this code inside:

using GLib;
using Gtk;
public class MyApp.MainWindow : Window {
   static int main (string[] args) {
      stdout.printf ("all data is in: " + Global.dataDir);
      return 0;
   }
}

After compilation, I get this string in terminal:
all data is in:

Seems that Global.dataDir is empty. Where is my mistake?
Thanks.

Non-value-type static class variables are only initialized after the
class was instantiated at least once. This behaviour is a little bit
counter-intuitive, and I hope it will change in the future.

You have several options:

- create a throw-away instance:

  static int main (string[] args) {
      new Global ();
      stdout.printf ("all data is in: " + Global.dataDir);
      return 0;
  }

- call a static initialization method:

  static int main (string[] args) {
      Global.init ();
      stdout.printf ("all data is in: " + Global.dataDir);
      return 0;
  }

- make 'dataDir' const, if it is not intended to change


Best regards,

Frederik



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