Search code examples
valagenie

What is the syntax for generic methods in Genie?


I found some code of Vala, and It works fine. but when I translate it to genie, it failed. So, my question is what's the equivalent code of Genie

int get_length<T> (T val) {
    if (typeof(T) == typeof(string) ) {
        return ((string)val).length;
    } else {
        GLib.error("Unable to handle type `%s'", typeof(T).name());
    }
}

public static void main() {
    var myString = "hello";
    stdout.printf("%i\n", get_length<string>(myString));
}

my code: genie

def get_length of T (val: T): int
    if typeof(T) == typeof(string)
        return ((string)val).length
    else
        pass
init
    var s = "hello";
    stdout.printf("%i", get_length of string (s))

The error message:

main.gs:2.16-2.17: error: syntax error, expected `(' but got `of' with previous identifier
def get_length of T (val: T): int
                ^^

update:

the code works.

init
    printx of int (123)
    printx (456)
    printx ("HELLO")

def printx (i: T) of T
    case typeof(T)
        when 64 // typeof(string)
            stdout.printf ("%s\n", (string)i)
        when 24 // typeof(int)
            stdout.printf ("%i\n", (int)i)

but if I want to have return value

I try

def doubleit (i: T): T of T

and the error messages:

2015-06-29_generic_func.gs:13.27-13.27: error: The type name `T' could not be found
def doubleit (i: T): T of T
                          ^
2015-06-29_generic_func.gs:13.22-13.27: error: The type name `T' could not be found
def doubleit (i: T): T of T
                     ^^^^^^
2015-06-29_generic_func.gs:13.18-13.18: error: The type name `T' could not be found
def doubleit (i: T): T of T
                 ^
Compilation failed: 3 error(s), 0 warning(s)

and try

def doubleit (i: T) of T : T

the error messages:

2015-06-29_generic_func.gs:13.26-13.26: error: syntax error, expected end of line but got `:' with previous identifier
def doubleit (i: T) of T : T
                         ^
Compilation failed: 1 error(s), 0 warning(s)

this code works in Vala:

T doubleit<T> (T i) {

Solution

  • As this doesn't seem possible at the moment I have reported it as a bug.