⚙️ Przeciążanie operatorów
Klasy mogą definiować własne zachowanie dla operatorów.
Przykład: Vector
class Vector {
init(x, y) {
this.x = x;
this.y = y;
}
operator +(other) {
return Vector(this.x + other.x, this.y + other.y);
}
operator -(other) {
return Vector(this.x - other.x, this.y - other.y);
}
operator *(scalar) {
return Vector(this.x * scalar, this.y * scalar);
}
operator ==(other) {
return this.x == other.x && this.y == other.y;
}
}
let v1 = Vector(1, 2);
let v2 = Vector(3, 4);
let sum = v1 + v2;
let scaled = v1 * 3;
print(v1 == v2);
Dostępne operatory
| Operator |
Metoda |
+ | operator +(other) |
- | operator -(other) |
* | operator *(other) |
/ | operator /(other) |
% | operator %(other) |
== | operator ==(other) |
!= | operator !=(other) |
< | operator <(other) |
> | operator >(other) |