HaxeDoc2

(やまだぃちぅ) #1
Variablexis first initialized to an emptyArray. At this point we can tell that the type ofxis an
array, but we do not yet know the type of the array elements. Consequentially, the type ofxis
Array<Unknown<0>>. It is only after pushing aStringonto the array that we know the type
to beArray<String>.

3.6.1 Top-down Inference


Most of the time, types are inferred on their own and may then be unified with an expected type.
In a few places, however, an expected type may be used to influence inference. We then speak of
top-down inference.

Definition: Expected Type
Expected types occur when the type of an expression is known before that expression has
been typed, e.g. because the expression is argument to a function call. They can influence
typing of that expression through what is called top-down inference (3.6.1).

A good example are arrays of mixed types. As mentioned inDynamic(Section 2.7), the com-
piler refuses[1, "foo"]because it cannot determine an element type. Employing top-down
inference, this can be overcome:
1 class Main {
2 static public function main() {
3 var a:Array = [1, "foo"];
4 }
5 }
Here, the compiler knows while typing[1, "foo"]that the expected type isArray,
so the element type isDynamic. Instead of the usual unification behavior where the compiler
would attempt (and fail) to determine a common base type (3.5.5), the individual elements are
typed against and unified withDynamic.
We have seen another interesting use of top-down inference when construction of generic
type parameters (3.3.1) was introduced:
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 }


The explicit typesStringandhaxe.Templateare used here to determine the return type
ofmake. This works because the method is invoked asmake(), so we know the return type will
be assigned to the variables. Utilizing this information, it is possible to bind the unknown type
TtoStringandhaxe.Templaterespectively.
Free download pdf