castingvala

Why `as` keyword is not casting in this code


as keyword is used in Vala for casting as mentioned on this page.

I see it being used in following code on this page:

FileOutputStream os = ios.output_stream as FileOutputStream;

However, it is not working in following code:

void main(){
    string ss = "5";
    stdout.printf("string ss = %s \n", ss);

    int i = ss as int; 
    stdout.printf("int i = %d \n", i); 
}

The error is:

$ valac mycode.vala
mycode.vala:6.10-6.18: error: Operation not supported for this type
    int i = ss as int; 
            ^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)

Where is the problem and how can it be solved?

Even integer cannot be casted to float:

void main(){
    int i = 5;
    stdout.printf("int i = %d \n", i);

    float f = i as float; 
    stdout.printf("int f = %f \n", f); 
}

Error is:

mycode.vala:6.12-6.22: error: Operation not supported for this type
    float f = i as float; 
              ^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)

Solution

  • Vala has two types of casting: static and dynamic type casting.

    Static casting (https://wiki.gnome.org/Projects/Vala/Tutorial#Static_Type_Casting) is done with parenthesis as in other languages like C:

    int i = 5;
    float f = (float) i;
    

    Dynamic casting (https://wiki.gnome.org/Projects/Vala/Tutorial#Dynamic_Type_Casting) is done with the as operator and only works on class types (OOP):

    Widget w = new Button();
    Button button = w as Button;
    

    When a dynamic cast fails (because the object is not compatible with the target type) the result will be null.

    In addition you can parse data (https://wiki.gnome.org/Projects/Vala/Tutorial#Strings), for example this will convert a string into an integer:

    string s = "5";
    int i = int.parse(s);
    

    The other way around there is a neat feature called string interpolation:

    int i = 5;
    string s = @"$i";
    

    Under the hood this just calls the to_string() method:

    int i = 5;
    string s = i.to_string();