HaxeDoc2

(やまだぃちぅ) #1
Definition: Structural Subtyping
Structural subtyping defines an implicit relation between types that have the same structure.

In Haxe, structural subtyping is only possible when assigning a class instance to a structure. The
following example is part of theLambdaclass of the Haxe Standard Library ( 10 ):
1 public static function
2 empty<T>(it : Iterable<T>):Bool {
3 return !it.iterator().hasNext();
4 }
Theempty-method checks if anIterablehas an element. For this purpose, it is not necessary
to know anything about the argument type other than the fact that it is considered an iterable.
This allows calling theempty-method with any type that unifies withIterable<T>which
applies to a lot of types in the Haxe Standard Library.
This kind of typing can be very convenient but extensive use may be detrimental to perfor-
mance on static targets, which is detailed inImpact on Performance(Section 2.5.4).

3.5.3 Monomorphs


Unification of types having or being a monomorph (2.9) is detailed inType Inference(Section 3.6).

3.5.4 Function Return...................................


Unification of function return types may involve theVoid-type (2.1.5) and requires a clear defi-
nition of what unifies withVoid. WithVoiddescribing the absence of a type, it is not assignable
to any other type, not evenDynamic. This means that if a function is explicitly declared as
returningDynamic, it cannot returnVoid.
The opposite applies as well: If a function declares a return type ofVoid, it cannot return
Dynamicor any other type. However, this direction of unification is allowed when assigning
function types:
1 var func:Void->Void = function()return "foo";
The right-hand function clearly is of typeVoid->String, yet we can assign it to the variable
funcof typeVoid->Void. This is because the compiler can safely assume that the return type
is irrelevant, given that it could not be assigned to any non-Voidtype.

3.5.5 Common Base Type


Given a set of multiple types, acommon base typeis a type which all types of the set unify against:
1 class Base {
2 public function new() { }
3 }
4
5 class Child1 extends Base {}
6 class Child2 extends Base {}
7
8 class UnifyMin {
9 static public function main() {
10 var a =[new Child1(), new Child2()];
11 $type(a); // Array

Free download pdf