Assign Default Attributes Values While Creating an Instance
Consider the following example where we're creating a window instance of the ApplicationWindow.
var window = new Gtk.ApplicationWindow(this);
Once the window instance is created, we can go ahead and assign some default values to the attributes such as default_height, default_width, and title like this.
window.default_height = 400; window.default_width = 200; window.title = "hello, world";
All-in-all, we can have the following code (if you want to try out from your side to see the output).
public class Application : Gtk.Application { public Application() { Object( application_id: "com.github.username.reponame", flags: ApplicationFlags.FLAGS_NONE ); } protected override void activate() { var window = new Gtk.ApplicationWindow(this); window.default_height = 350; window.default_width = 280; window.title = "hello, world"; window.show_all(); } } int main(string[] args) { var application = new Application(); return application.run(args); }
Vala provide a way to define the attributes' default values at the time of instance creation. In this way, we don't have to write it separately and we don't have to prefix each property with instance name. We can mentioned the properties in curly brackets.
This is how we can create an instance of ApplicationWindow, right!
var window = new Gtk.ApplicationWindow(this);
Instead of terminating the statement with semicolon at the end, let's add the curly brackets.
var window = new Gtk.ApplicationWindow(this) { };
Within this curly brackets, let's assign the default values to
attributes without prefixing the window and separate them by comma.
var window = new Gtk.ApplicationWindow(this) { default_height = 350, default_width = 280, title = "hello, world" };
Don't forget to add ; after the closing curly bracket.
I find this lot cleaner! Here is the complete code, if you're interested to run.
public class Application : Gtk.Application { public Application() { Object( application_id: "com.github.username.reponame", flags: ApplicationFlags.FLAGS_NONE ); } protected override void activate() { var window = new Gtk.ApplicationWindow(this) { default_height = 350, default_width = 280, title = "hello, world" }; window.show_all(); } } int main(string[] args) { var application = new Application(); return application.run(args); }
This is applicable to almost all Gtk widgets.
---