Velo by Example: Operator Overloading

Classes can define custom behavior for built-in operators using the operator keyword. Velo supports arithmetic, comparison, unary, and index operators.

Define binary operators like +, -, *, / inside a class.

class Vector(int x, int y) {
    operator +(Vector other) Vector {
        new Vector(x + other.x, y + other.y);
    };

    operator -(Vector other) Vector {
        new Vector(x - other.x, y - other.y);
    };
};

Vector a = new Vector(1, 2);
Vector b = new Vector(3, 4);
Vector sum = a + b;    # Vector(4, 6)

Comparison operators return bool.

class Vector(int x, int y) {
    operator ==(Vector other) bool {
        x == other.x & y == other.y;
    };

    operator <(Vector other) bool {
        x < other.x & y < other.y;
    };
};

bool eq = a == a;      # true
bool lt = a < b;       # true

Unary negation takes no parameters. The compiler distinguishes it from binary - by the parameter count.

class Vector(int x, int y) {
    operator -() Vector {
        new Vector(0 - x, 0 - y);
    };
};

Vector neg = -a;       # Vector(-1, -2)

Index operators enable bracket-based read and write access.

class Vector(int x, int y) {
    operator [](int index) int {
        if (index == 0) then x else y;
    };

    operator []=(int index, int value) void {
        if (index == 0) then x = value
        else y = value;
    };
};

Vector v = new Vector(0, 0);
v[0] = 10;
v[1] = 20;
int first = v[0];      # 10

Compound assignment (+=, -=, etc.) works automatically — it desugars to a = a + b.

Vector v = new Vector(1, 2);
v = v + new Vector(10, 10);
# v is now Vector(11, 12)