HaxeDoc2

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

9 Main.main = function() {
10 var s = Main.make_String();
11 var t = Main.make_haxe_Template();
12 }


3.4 Variance


While variance is also relevant in other places, it occurs particularly often with type parameters
and comes as a surprise in this context. Additionally, it is very easy to trigger variance errors:
1 class Base {
2 public function new() { }
3 }
4
5 class Child extends Base {}
6
7 class Main {
8 public static function main () {
9 var children =[new Child()];
10 // Array should be Array
11 // Type parameters are invariant
12 // Child should be Base
13 var bases:Array=children;
14 }
15 }


Apparently, anArraycannot be assigned to anArray, even thoughChild
can be assigned toBase. The reason for this might be somewhat unexpected: It is not allowed
because arrays can be written to, e.g. via theirpush()method. It is easy to generate problems
by ignoring variance errors:
1 class Base {
2 public function new() { }
3 }
4
5 class Child extends Base {}
6
7 class OtherChild extends Base {}
8
9 class Main {
10 public static function main () {
11 var children =[new Child()];
12 // subvert type checker
13 var bases:Array=castchildren;
14 bases.push(new OtherChild());
15 for(child in children){
16 trace(child);
17 }
18 }
19 }

Free download pdf