3.3.1 Construction of generic type parameters

Define: Generic Type Parameter

A type parameter is said to be generic if its containing class or method is generic.

It is not possible to construct normal type parameters; for example, new T() would register as a compiler error. The reason for this is that Haxe generates only a single function and the construct would make no sense in that case. This is different when the type parameter is generic: since we know that the compiler will generate a distinct function for each type parameter combination, it is possible to replace the T new T() with the real type.

import haxe.Constraints;

class Main {
  static public function main() {
    var s:String = make();
    var t:haxe.Template = make();
  }

  @:generic
  static function make<T:Constructible<String->Void>>():T {
    return new T("foo");
  }
}

It should be noted that top-down inference is used here to determine the actual type of T. For this kind of type parameter construction to work, the constructed type parameter must meet two requirements:

  1. It must be generic.
  2. It must be explicitly constrained to have a constructor.

Here, the first requirement is met by make having the @:generic metadata, and the second by T being constrained to Constructible. The constraint holds for both String and haxe.Template as both have a constructor accepting a singular String argument. Sure enough, the relevant JavaScript output looks as expected:

var Main = function() { }
Main.__name__ = true;
Main.make_haxe_Template = function() {
    return new haxe.Template("foo");
}
Main.make_String = function() {
    return new String("foo");
}
Main.main = function() {
    var s = Main.make_String();
    var t = Main.make_haxe_Template();
}