简体   繁体   中英

Generics class method taking function parameter of the generic type doesn't work with Void

I've run into a Haxe issue that seems really odd to me.. Is it a bug ?

When creating a generic class with a method taking a function of the generic type as a parameter i get the weird error

Void -> Void should be (Void) -> Void

When the generic type is Void

If the generic type is Int it works fine.

Does anyone have any ideas to fix or work around this ?

Playground link

class Test {
    static var test2:Test2<Void> = new Test2<Void>();
    static public function main() {
        test2.test(passedFunc);
    }

    static function passedFunc():Void {
        trace("passedFunc");
    }
}

class Test2<T> {
    public function new():Void {}

    public function test(func: T->Void) {
        trace("Test2.testFunc(T)");
    }
}

I'm not sure that it's a bug, it could just be related to the way the Type system works in Haxe. In any case, one workaround you could use is to simply have a function where the parameter is explicity typed Void->Void and use your parameterized type T in other functions of the class when necessary.

Workaround:

static public function main() {
    test2.test(cast passedFunc);
}

Playground link .

You can trick the type inference to almost ignore the missing argument like so:

class Test {
    static var test2 = new Test2();
    static public function main() {
        test2.test(passedFunc);
    }
    static function passedFunc(?unused):Void {
        trace("passedFunc");
    }
}    
class Test2<T> {
    public function new():Void {}
    public function test(func: T->Void) {
        trace("Test2.testFunc(T)");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM