Operator overloading is only possible with abstract types.
The following abstract defines a Vec2i
type based on the Array<Int>
type. This is a two-component vector with integer values. Operator overloading is made possible my the @:op
compiler metadata. Only the available numeric operators can be overloaded - custom operators are not allowed to be specified.
abstract Vec2i(Array<Int>) {
public inline function getX() : Int {
return this[0];
}
public inline function getY() : Int {
return this[1];
}
public inline function new(x : Int, y : Int) {
this = [x, y];
}
@:op(A + B)
public inline function add(B : Vec2i) : Vec2i {
return new Vec2i(
getX() + B.getX(),
getY() + B.getY()
);
}
}
Use the abstract as follows.
var v1 = new Vec2i(1, 2);
var v2 = new Vec2i(3, 4);
v1 + v2;
v1.add(v2);
Try the example on try.haxe.org.