HaxeDoc2

(やまだぃちぅ) #1
Definition: Static Extension
A static extension allows pseudo-extending existing types without modifying their source.
In Haxe this is achieved by declaring a static method with a first argument of the extending
type and then bringing the defining class into context throughusing.

Static extensions can be a powerful tool which allows augmenting types without actually chang-
ing them. The following example demonstrates the usage:
1 using Main.IntExtender;
2
3 class IntExtender {
4 static public function triple(i:Int){
5 return i * 3;
6 }
7 }
8
9 class Main {
10 static public function main() {
11 trace(12.triple());
12 }
13 }


Clearly,Intdoes not natively provide atriplemethod, yet this program compiles and out-
puts 36 as expected. This is because the call to12.triple()is transformed intoIntExtender.triple(12).
There are three requirements for this:

1.Both the literal 12 and the first argument oftripleare of typeInt.

2.The classIntExtenderis brought into context throughusing Main.IntExtender.

3.Intdoes not have atriplefield by itself (if it had, that field would take priority over the
static extension).

Static extensions are usually considered syntactic sugar and indeed they are, but it is worth
noting that they can have a dramatic effect on code readability: Instead of nested calls in the form
off1(f2(f3(f4(x)))), chained calls in the form ofx.f4().f3().f2().f1()can be used.
Following the rules previously described inResolution Order(Section 3.7.3), multipleusing
expressions are checked from bottom to top, with the types within each module as well as the
fields within each type being checked from top to bottom. Using a module (as opposed to a
specific type of a module, seeModules and Paths(Section 3.7)) as static extension brings all its
types into context.

6.3.1 In the Haxe Standard Library...........................


Several classes in the Haxe Standard Library are suitable for static extension usage. The next
example shows the usage ofStringTools:
1 using StringTools;
2
3 class Main {
4 static public function main() {
5 "adc".replace("d", "b");
6 }
7 }
Free download pdf