Search code examples
genericsvala

Vala - Print generic value


I am trying to create a generic class that is able to print out it's values.

class Point<T>
{ 
    public T x {get; set; default = 0;}
    public T y {get; set; default = 0;}

    public void print()
    {
        stdout.puts(@"x: $x, y: $y\n");
    }
}

int main(string[] args)
{
    var point = new Point<int>();
    point.x = 12;
    point.y = 33;
    point.print();

    return 0;
}

The compiler gives me these errors:

main.vala:8.21-8.22: error: The name `to_string' does not exist in the context of `T'
        stdout.puts(@"x: $x, y: $y\n");
                         ^^
main.vala:8.28-8.29: error: The name `to_string' does not exist in the context of `T'
        stdout.puts(@"x: $x, y: $y\n");
                                ^^

Is there a way to work this out?


Solution

  • Not directly. You'll need to pass in a delegate to print your item:

    delegate string Stringify<T>(T item);
    class Point<T>
    { 
        public T x {get; set; default = 0;}
        public T y {get; set; default = 0;}
    
        public void print(Stringify<T> stringifier)
        {
            stdout.puts(@"x: $(stringifier(x)), y: $(stringifier(y))\n");
        }
    }
    int main(string[] args)
    {
        var point = new Point<int>();
        point.x = 12;
        point.y = 33;
        point.print(int.to_string);
        return 0;
    }
    

    Alternatively, you can build a set of special cases as Gee does: https://github.com/GNOME/libgee/blob/master/gee/functions.vala#L49