LEVIATHAN vd52e79c4 · d52e79c486

Expressions

Operators on objects

A class defines the meaning of an operator by declaring a member with a symbolic selector; the equality operator derives its negation automatically.

since 0.1.0-alpha.1linuxwindowswasm

Description

For a op b where a is an object, the compiler looks up the member named (op) on a's class and picks the overload that fits the type of b. A class may declare several overloads of one operator for different right-hand types.

An operator is declared as a member with a symbolic selector in parentheses: Money (+)(Money other) => ...;, bool (==)(Money other) => ...;.

(==) must return bool. You never write (!=) yourself: a != b is derived as !(a == b).

Operator members

use io::console;

class Money {
    int cents;
    Money (+)(Money other) => Money(cents + other.cents);
    bool (==)(Money other) => cents == other.cents;
    bool (<)(Money other) => cents < other.cents;
    string toString() => "${cents} cents";
}

Money a = Money(150);
Money b = Money(250);
console.writeln((a + b).toString());
console.writeln(a == Money(150));
console.writeln(a != b);
console.writeln(a != Money(150));
console.writeln(a < b);
400 cents
true
true
false
true

Rules

  • The operator member is chosen on the type of the left operand, and the overload on the type of the right operand, at compile time from the static types. The call then dispatches like a method call (see lang.method-dispatch): when a subclass of the left operand's static type overrides the chosen operator and the operand holds that subclass, the override runs. It is the override of the chosen overload: another overload of the same symbol that only the subclass declares never answers the call. The same holds where the language calls an operator for you: a match value arm (==), a range arm (>= and <=), a compound assignment and a derived !=.
  • An overridden operator may have other overloads of the same symbol: every binary operator takes one operand, so they all have one parameter, and the use still runs the override of the overload the right operand chose, as for a method. An overload that no subclass overrides is called directly. As for a method, one operator cannot stand for two overloads that a generic base's type arguments make one signature ((==)(T x) and (==)(string s) under V<string>): that is a compile error at the declaration (see lang.method-dispatch). An operator on a value of an erased type parameter T is chosen by its symbol alone and runs the bound type's overload declared first, so a binding whose use needs another overload is a compile error (see lang.generics).
  • An operator that an interface declares has no body. When the left operand's static type is that interface, the runtime class's implementation of that operator runs, the same way an interface method call is dispatched (see lang.method-dispatch).
  • On a generic class, the overload is chosen with the left operand's type arguments substituted into its parameters, exactly as for a method call: for Vec<int> v, v + 5 picks (+)(T x) over (+)(Vec<T> o), because T is int. An operator inherited from a generic base (class IntVec : Vec<int>) sees the base's arguments, and this + x inside the generic class itself matches x against its own type parameter T.
  • A class whose (+) has an overload accepting a string runs that overload for a + "text"; the result is the overload's, not string concatenation.
  • A class that declares the operator but has no overload accepting the right operand's type is a compile error, no overload of '(+)' on 'Money' accepts 'bool', with a note for each overload saying why it does not apply. A string right operand is no exception: when the class declares (+), a + "text" needs an overload that accepts the string.
  • a op= b runs the same overload as a op b and stores the result in a.
  • (==) must return bool.
  • != is derived from == as its negation. Declaring only (==) is enough. The derivation needs a (==) that returns bool: with any other return type, a != b is a compile error unless the class declares its own (!=).
  • The same operator can be both a built-in operation and a user operation: + adds two int values and also calls a class's (+). Which one applies depends on the operand types.
  • A binary operator, or its compound form such as +=, used on an object whose static type declares no member for that operator is a compile error: no operator '+' on 'Plain'. The type's members include the ones it inherits from a base class or declares through an interface. The operator is looked up on the declared type of the left operand, so a member that only a subclass declares is not found through a base-class variable.
  • == and != need no declared member: without a (==), a class compares by identity, and a value struct uses its derived field-by-field equality (see lang.structs).
  • The prefix operators -, ! and ~ cannot be declared on a class, so applying one to an object is a compile error. See lang.prefix-operators.

Examples

Overloads chosen by the right operand

use io::console;

class Money {
    int cents;
    Money (+)(Money other) => Money(cents + other.cents);
    Money (+)(int extra) => Money(cents + extra);
    Money (+)(string tag) => Money(cents + tag.length() * 1000);
    bool (==)(int c) => cents == c;
    string toString() => "${cents} cents";
}

Money a = Money(150);
console.writeln((a + Money(100)).toString());
console.writeln((a + 5).toString());
console.writeln((a + "ab").toString());
console.writeln(a != 150);
250 cents
155 cents
2150 cents
false

An override runs from a base-typed variable

use io::console;

class Money {
    int cents;
    new Money(int c) { cents = c; }
    bool (==)(int c) => cents == c;
    Money (+)(int c) => Money(cents + c);
}

class Rounded : Money {
    new Rounded(int c) { cents = c; }
    bool (==)(int c) => cents / 100 == c / 100;
    Money (+)(int c) => Rounded(cents + c - c % 100);
}

Money m = Rounded(250);
console.writeln(m == 299);
m = m + 120;
console.writeln(m.cents);
m += 5;
console.writeln(m.cents);
console.writeln(match (m) { 300 => "about three hundred"; else => "other" });
Money plain = Money(250);
console.writeln(plain == 299);
true
350
350
about three hundred
false

An operator declared by an interface

use io::console;

interface Scalable {
    int (*)(int k);
}

class Meters : Scalable {
    int m;
    int (*)(int k) => m * k;
}

class Feet : Scalable {
    int f;
    int (*)(int k) => f * k * 3;
}

Array<Scalable> xs = [Meters(2), Feet(1)];
for (Scalable x in xs) {
    console.writeln(x * 10);
}
20
30

Overloads on a generic class

use io::console;

class Vec<T> {
    Array<T> xs = [];
    Vec<T> (+)(Vec<T> o) { Vec<T> r = Vec::<T>(); r.xs = xs.concat(o.xs); return r; }
    Vec<T> (+)(T x) { Vec<T> r = Vec::<T>(); r.xs = xs; r.xs.add(x); return r; }
}

Vec<int> v = Vec::<int>();
Vec<int> w = v + 5;
Vec<int> both = w + w;
console.writeln(w.xs.length());
console.writeln(both.xs.length());
1
2
use io::console;

class Plain {
    int v = 1;
}

Plain p = Plain();
console.writeln(p + p);
// error: no operator '+' on 'Plain'
p += p;
// error: no operator '+' on 'Plain'
console.writeln(p == p);   // allowed: identity comparison
not run — shows a compile error

Notes

Indexing with [] is declared the same way, with the selector ([]). See lang.indexing.

See also

  • int — The signed 64-bit integer type, the default type of whole numbers.
  • Indexing — The square-bracket operator reads and writes elements through an indexer accessor, and rebinds the variable when the target is an array.
  • Prefix operators — The operand types accepted by the unary operators !, - and ~, and the results they produce.
  • Value structs — Declare value types that are copied on every assignment, pass and return, with derived equality and explicit mutating methods.