Overloading
Defining Custom Operator Behavior

In languages like Java, you cannot change how operators work, with minor exceptions like the obj.toString() method.

In C++, you can change the behavior of operators.

In Mint you can do the same. In the file overload.mint, which should
be in the same folder as the Mint JAR file, you can edit
some subprograms to let primitive Mint operators perform
special actions on objects.

Assume you have the following class-like subprograms:
sub Vector(x0, y0)
    type = "vect"
    horizCoord = x0
    vertCoord = y0
    return this
end

sub Sphere(radius)
    type = "sphere"
    r = radius
    return this
end

sub Number(value)
    type = "number"
    val = value
    return this
end

vec0 = Vector(7, 4)
vec1 = Vector(15, -5)
sphere0 = Sphere(60)
print vec0 + vec1
print sphere0 * Number(3)
In the overload.mint file, you define:
sub plus(x, y)
    when x.type == "vect"
        return [x.horizCoord + y.horizCoord, x.vertCoord + y.vertCoord]
end

sub times(x, y)
    when x.type == "sphere" and y.type == "number"
        return [x.r * y.val]
end
Running program.mint will print [22, -1] and then [180].
The code emulates the addition of vectors and inflating a sphere with some atmospheric gas.

Navigation
Previous Lesson: Imports
Next Lesson: Documentation
Table of Contents