What does the class keyword do to a method in Vala?

55 views Asked by At

I noticed that Gtk.Widget.set_css_name is declared as public class void set_css_name (string name) which makes sense because in C the argument is a GtkWidgetClass* and not a GtkWidget*. This means that you can call set_css_name inside a static construct block in a class that derives from Gtk.Widget:

static construct {
    set_css_name ("foobar");
}

I also noticed that you can define your own class methods:

public class void foobar () {

}

However, you are not allowed to access this inside such a method:

error: This access invalid outside of instance methods
        this;
        ^^^^

This makes me wonder: How do I actually access the GObjectClass inside a class method? Let's say I want to call Gtk.BindingSet.by_class which takes the class as an argument. How do I do that?

I couldn't find any documentation on these kinds of methods. What is the name of this feature and is there any documentation available? Could someone please explain this feature in detail?

1

There are 1 answers

0
scrutari On

Some information on this can be found in this answer: https://stackoverflow.com/a/40068901/547270.

In a nutshell, the class keyword used in a member declaration (a field or a method) makes is a "class" member as opposed to "instance" and "static" members. In most OOP languages are present and "class" member is somewhat unusual.

As explained in the answer linked above, the difference between the "class" and "static" members is important for fields while for methods, I think, it is safe to say that they behave exactly as instance methods. So, for example:

public class Test {
    public class int class_method(int a, int b) {
        return a + b;
    }
}

you would need to have an instance in order to call this method:

var test = new Test();
var u = test.class_method(2, 3);

I suppose class methods are a peculiar corner case of GObject.