Interfaces, operators and equality
Interfaces
An interface lists public methods. A class implements it by saying so with implements
and providing each method with exactly the same parameter and return types.
interface Damageable {
damage(amount: int): int;
}
class Barrel implements Damageable {
hp: int = 10;
damage(amount: int): int { this.hp -= amount; return this.hp; }
}
class Wall implements Damageable {
damage(amount: int): int { return 99; }
}
function hit(target: Damageable): int { return target.damage(4); }
export function main(): void {
let target: Damageable = new Barrel();
print(hit(target), hit(target));
target = new Wall();
print(hit(target));
}
6 2
99
- Interfaces declare methods only. A field in an interface is an error
(
interfaces declare method signatures). - Conversion to an interface needs the explicit
implements; matching method names alone are not enough. - Calls through an interface dispatch through a table of function pointers. Two interface values compare equal when they refer to the same object.
- Interface values contain pointers into the current gameplay module, so don't keep them across a code reload (store the class reference instead).
Operators
Structs and classes can define +, -, *, /, ==, [] and unary -. Compound
assignment (+= and friends) and != follow automatically.
struct Money {
cents: int;
operator +(other: Money): Money { return Money(this.cents + other.cents); }
operator -(other: Money): Money { return Money(this.cents - other.cents); }
operator -(): Money { return Money(-this.cents); }
operator *(factor: int): Money { return Money(this.cents * factor); }
operator ==(other: Money): bool { return this.cents == other.cents; }
operator [](i: int): int { return this.cents + i; }
}
export function main(): void {
let wallet = Money(250);
wallet += Money(50);
wallet = wallet * 2;
print(wallet.cents, (-wallet).cents, wallet == Money(600), wallet != Money(600), wallet[1]);
}
600 -600 true false 601
- Operators are instance members. The left operand decides which operator is used.
- Unary and binary
-are told apart by the number of parameters. - A struct operator receives a copy of the left operand as
this. []returns a value; you can't assign through it.
Equality
== and != are strict: both sides must have the same type, with no conversions.
| Type | == means |
|---|---|
Numbers, bool |
Same value and same type (1 == 1.0 is an error) |
string |
Same bytes |
| Vectors, matrices | Every component equal |
| Struct | Only if the struct defines operator == (otherwise operator '==' does not accept S and S) |
| Class | Reference identity, unless the class defines operator == |
Handle<T> |
Same object (index and generation) |
| Nullable values | Two absent values are equal; x == null tests presence |
When a class defines operator == and both sides are present nullable references, the
operator is used.