HaxeDoc2

(やまだぃちぅ) #1

5
6 @:op(A B)
7 public function repeat(rhs:Int):MyAbstract {
8 var s:StringBuf = new StringBuf();
9 for (i in 0...rhs)
10 s.add(this);
11 return new MyAbstract(s.toString());
12 }
13 }
14
15 class AbstractOperatorOverload {
16 static public function main() {
17 var a = new MyAbstract("foo");
18 trace(a
3); // foofoofoo
19 }
20 }


By defining@:op(A B), the functionrepeatserves as operator method for the multiplica-
tion
operator when the type of the left value isMyAbstractand the type of the right value is
Int. The usage is shown in line 17, which turns into this when compiled to Javascript:
1 console.log(_AbstractOperatorOverload.
2 MyAbstractImpl.repeat(a,3));
Similar to implicit casts with class fields (2.8.1), a call to the overload method is inserted where
required.
The examplerepeatfunction is not commutative: WhileMyAbstract * Intworks,Int



  • MyAbstractdoes not. If this should be allowed as well, the@:commutativemetadata can
    be added. If it should workonlyforInt MyAbstract, but not forMyAbstract Int, the
    overload method can be made static, acceptingIntandMyAbstractas first and second type
    respectively.
    Overloading unary operators is analogous:
    1 abstract MyAbstract(String){
    2 public inline function new(s:String){
    3 this = s;
    4 }
    5
    6 @:op(++A) public function pre()
    7 return "pre" + this;
    8 @:op(A++) public function post()
    9 return this + "post";
    10 }
    11
    12 class AbstractUnopOverload {
    13 static public function main() {
    14 var a = new MyAbstract("foo");
    15 trace(++a); // prefoo
    16 trace(a++); // foopost
    17 }
    18 }


Both binary and unary operator overloads can return any type.
Free download pdf