HaxeDoc2

(やまだぃちぅ) #1
10 }

11 Main.main();
12 })();


3.3.1 Construction of generic type parameters


Definition: 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, e.g. new T()is a compiler error. The
reason for this is that Haxe generates only a single function and the construct makes 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.
1 typedef Constructible ={
2 public function new(s:String):Void;
3 }
4
5 class Main {
6 static public function main() {
7 var s:String = make();
8 var t:haxe.Template = make();
9 }
10
11 @:generic
12 static function make():T {
13 return new T("foo");
14 }
15 }


It should be noted that top-down inference (3.6.1) is used here to determine the actual type
ofT. There are two requirements for this kind of type parameter construction to work: The con-
structed type parameter must be

1.generic and

2.be explicitly constrained (3.2.1) to having a constructor (2.3.1).

Here, 1. is given bymakehaving the@:genericmetadata, and 2. byTbeing constrained to
Constructible. The constraint holds for bothStringandhaxe.Templateas both have a
constructor accepting a singularStringargument. Sure enough, the relevant Javascript output
looks as expected:
1 var Main = function() { }
2 Main.__name__ = true;
3 Main.make_haxe_Template = function() {
4 return new haxe.Template("foo");
5 }
6 Main.make_String = function() {
7 return new String("foo");
Free download pdf