HaxeDoc2

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

13 }

AlthoughBaseis not mentioned, the Haxe Compiler manages to infer it as the common type
ofChild1andChild2. The Haxe Compiler employs this kind of unification in the following
situations:


  • array declarations

  • if/else

  • cases of aswitch


3.6 Type Inference........................................


The effects of type inference have been seen throughout this document and will continue to be
important. A simple example shows type inference at work:
1 class TypeInference {
2 public static function main() {
3 var x = null;
4 $type(x); // Unknown<0>
5 x = "foo";
6 $type(x); // String
7 }
8 }
The special construct$typewas previously mentioned in order to simplify the explanation of
theFunction Type(Section 2.6) type, so let us now introduce it officially:

Construct:$type
$typeis a compile-time mechanism being called like a function, with a single argument. The
compiler evaluates the argument expression and then outputs the type of that expression.

In the example above, the first$typeprintsUnknown<0>. This is a monomorph (2.9), a type
that is not yet known. The next linex = "foo"assigns aStringliteral tox, which causes
the unification (3.5) of the monomorph withString. We then see that the type ofxindeed has
changed toString.
Whenever a type other thanDynamic(Section 2.7) is unified with a monomorph, that monomorph
becomesthat type: itmorphsinto that type. Therefore it cannot morph into a different type after-
wards, a property expressed in themonopart of its name.
Following the rules of unification, type inference can occur in compound types:
1 class TypeInference2 {
2 public static function main() {
3 var x = [];
4 $type(x); // Array<Unknown<0>>
5 x.push("foo");
6 $type(x); // Array<String>
7 }
8 }
Free download pdf