Vala - Print total cost

I am trying to create a generic class capable of printing its 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 the following 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 handle this?

+3


source to share


1 answer


Not directly. You will need to pass a delegate to print your element:

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 create a set of special cases, like Gee: https://github.com/GNOME/libgee/blob/master/gee/functions.vala#L49

+4


source







All Articles