COMMUNITY

Operator Overloading: "should be Int" compilation error

Hello,

I’m pretty new in the Haxe ecosystem and I don’t understand why this piece of code is failing with a “should be Int” compilation error:

class Test {
    static function main() {
        var v1 = new Vec2(1, 2);
        v1 * 2.0;
        trace(v1.x + " " + v1.y);
    }
}

class Vec2
{
    public inline function new(x : Float, y : Float) {
        this.x = x;
        this.y = y;
    }
    
    @:op(A * B) @:commutative
    public inline function multiply(B : Float) : Vec2 {
        return new Vec2(x * B, y * B);
    }
    
    //@:op(A * B) @:commutative
    //public static function multiply(A:Vec2, B:Float):Vec2 {
    //	  A.x *= B;
    //    A.y *= B;
    //    return A;
	//}
    
    public var x:Float;
    public var y:Float;
}

This can easily tested in https://try.haxe.org

Thanks in advance for your help.

Best,
Aurélien

Operator overloading on classes is not supported and the compiler expects Int by default for arithmetic operations.

You need something like this:

class Test {
    static function main() {
        var v1 = new Vec2(1, 2);
        var v2 = v1 * 2.0;
        trace(v1.x + " " + v1.y);
        trace(v2.x + " " + v2.y);
    }
}

@:forward 
enum abstract Vec2(Vec2Impl) from Vec2Impl to Vec2Impl {
    public inline function new(x : Float, y : Float) {
        this = {x:x,y:y};
    }
    
    @:op(A * B) @:commutative
    public inline function multiply(B : Float) : Vec2 {
        return new Vec2(this.x * B, this.y * B);
    }
}

typedef Vec2Impl = {x:Float, y:Float}
3 Likes