HaxeDoc2

(やまだぃちぅ) #1

2.8.6 Forwarding abstract fields.............................


Since Haxe 3.1.0

When wrapping an underlying type, it is sometimes desirable to “keep” parts of its function-
ality. Because writing forwarding functions by hand is cumbersome, Haxe allows adding the
:forwardmetadata to an abstract type:
1 @:forward(push, pop)
2 abstract MyArray(Array) {
3 public inline function new() {
4 this = [];
5 }
6 }
7
8 class Main {
9 static public function main() {
10 var myArray = new MyArray();
11 myArray.push(12);
12 myArray.pop();
13 // MyArray has no fieldlength
14 //myArray.length;
15 }
16 }


TheMyArrayabstract in this example wrapsArray. Its:forwardmetadata has two ar-
guments which correspond to the field names to be forwarded to the underlying type. In this
example, themainmethod instantiatesMyArrayand accesses itspushandpopmethods. The
commented line demonstrates that thelengthfield is not available.
As usual we can look at the Javascript output to see how the code is being generated:
1 Main.main = function() {
2 var myArray = [];
3 myArray.push(12);
4 myArray.pop();
5 };
It is also possible to use:forwardwithout any arguments in order to forward all fields. Of
course the Haxe Compiler still ensures that the field actually exists on the underlying type.

Trivia: Implemented as macro
Both the:enumand:forwardfunctionality were originally implemented using build
macros (9.5). While this worked nicely in non-macro code, it caused issues if these features
were used from within macros. The implementation was subsequently moved to the com-
piler.

2.8.7 Core-type abstracts.................................


The Haxe Standard Library defines a set of basic types as core-type abstracts. They are identified
by the:coreTypemetadata and the lack of an underlying type declaration. These abstracts can
still be understood to represent a different type. Still, that type is native to the Haxe target.