Trivia: Type parameters in expression syntax
We often get the question why a method with type parameters cannot be called as
method<String>(x). The error messages the compiler gives are not very helpful. How-
ever, there is a simple reason for that: The above code is parsed as if both<and>were binary
operators, yielding(method < String) > (x).
3.2.1 Constraints
Type parameters can be constrained to multiple types:
1 typedef Measurable ={
2 public var length(default, null):Int;
3 }
4
5 class Constraints {
6 static public function main() {
7 trace(test([]));
8 trace(test(["bar", "foo"]));
9 // String should be Iterable
10 //test("foo");
11 }
12
13 static function
14 test<T:(Iterable
15 if (a.length == 0) return "empty";
16 return a.iterator().next();
17 }
18 }
Type parameterTof methodtestis constrained to the typesIterable<String>andMeasurable.
The latter is defined using a typedef (3.1) for convenience and requires compatible types to have
a read-only property (4.2) namedlengthof typeInt. The constraints then say that a type is
compatible if
- it is compatible withIterable
and - has alength-property of typeInt.
We can see that invokingtestwith an empty array in line 7 and anArray<String>in line
8 works fine. This is becauseArrayhas both alength-property and aniterator-method.
However, passing aStringas argument in line 9 fails the constraint check becauseStringis
not compatible withIterable<T>.
3.3 Generic............................................
Usually, the Haxe Compiler generates only a single class or function even if it has type param-
eters. This results in a natural abstraction where the code generator for the target language has
to assume that a type parameter could be of any type. The generated code then might have to
perform some type checks which can be detrimental to performance.
A class or function can be madegenericby attributing it with the:genericmetadata (6.9).
This causes the compiler to emit a distinct class/function per type parameter combination with