COMMUNITY

Can anyone help me find out why this is a compilation failure when calling a generic function to return a type with a generic argument?


(Skyler Parr) #1

Hard to explain, but here’s my code I’m trying to get working:

@:generic
class Foo<T> {
  public function new() {
  }
}

class TestFoo {
  public static function test(): Void {
    var f: Foo<String> = createFoo<String>("foo");
    trace(f);
  }

  @:generic
  public static inline function createFoo<T>(v: T): Foo<T> {
    return new Foo<T>();
  }
}

When running the compiler, I get:
characters 25-41 : Cannot compare v : Unknown<0> -> Foo<Unknown<0>> and Class<String>

I figured this would work, but it doesn’t. Can anyone explain to me why it won’t work and how I can work around it (without using a macro)?

Thank you so much!


(Jens Fischer) #2

Simply because Haxe doesn’t parse that as a function call with <String> as the type paramter, but as a comparison (createFoo < String). Of course, the typer then complains that it doesn’t make sense to compare those things. :slight_smile:

See also: https://haxe.org/manual/type-system-type-parameters.html#trivia:-type-parameters-in-expression-syntax

Explicit type parameters are only allowed for constructor calls (e.g. new Array<Int>()), but not regular functions. Related GitHub issue: https://github.com/HaxeFoundation/haxe/issues/3666