Operator Overloading
Operators are instance methods with special names.
Dart allows you to define operators with the following names:
< |
+ |
| |
[] |
> |
/ |
^ |
[]= |
<= |
~/ |
& |
~ |
>= |
* |
<< |
== |
– |
% |
>> |
To overload operators, we use: the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Example :
The following example defines Point multiplication (*), addition (+) and subtraction (-)
class Point {
final int x, y, z;
Point(this.x, this.y, this.z);
Point operator +(Point v) => Point(x + v.x, y + v.y, z + v.z);
Point operator -(Point v) => Point(x - v.x, y - v.y, z - v.z);
Point operator *(Point v) => Point(x * v.x, y * v.y, z * v.z);
void display() {
print("x : $x --- y : $y --- z : $z");
}
}
void main() {
final a = Point(1, 3, 2);
final b = Point(4, 7, 5);
var c = a + b;
var d = b - a;
var e = b * a;
c.display();
d.display();
e.display();
}
x : 3 --- y : 4 --- z : 3
x : 4 --- y : 21 --- z : 10
Note:
You may have noticed that some operators, like !=, are not in the list of names. That’s because they’re just syntactic sugar. For example, the expression e1 != e2 is syntactic sugar for !(e1 == e2).