CodeBlanks Logo Icon CodeBlanks

Extension operator

Learn extension operator overloading.

Extension operator

Extension operator is operator overloading within an extension. The extension VectorOps on Vector { Vector operator +(Vector other) => ... } declaration redefines the + operator for Vector.

Operator overloading allows custom operations with natural syntax: v1 + v2 adds two Vectors. Dart allows overloading many operators like + - * / == < >. Each operator has a fixed signature.

Operator rules

In Dart, each operator has a fixed signature. operator + takes one parameter and the return type is free. operator == must return bool and should be consistent with hashCode when possible.

Some operators cannot be overloaded: =, !, ??, ., ~/ (except ~/=). operator [] and operator []= are used for indexing. Logical operators (&&, ||) cannot be overloaded.

Practice A Vector + operator

Define a Vector class with final int x; final int y; const Vector(this.x, this.y); field and constructor. Define a VectorOps extension on Vector with a Vector operator +(Vector other) => Vector(x + other.x, y + other.y); method. In main create final v = Vector(1, 2) + Vector(3, 4);; print with print('${v.x},${v.y}');.

Starter code

main.dart
void main() {
  // define a Vector class and a VectorOps extension
  // print Vector(1,2) + Vector(3,4)
}

Sample solution

main.dart
class Vector {
  final int x;
  final int y;
  const Vector(this.x, this.y);
}

extension VectorOps on Vector {
  Vector operator +(Vector other) => Vector(x + other.x, y + other.y);
}

void main() {
  final v = Vector(1, 2) + Vector(3, 4);
  print('${v.x},${v.y}');
}

Expected output

4,6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the operators

Term Meaning
operator + Addition
operator == Equality
operator < Less than
operator * Multiplication

2 What must operator == return?

  • int
  • bool Correct answer
  • String
  • void

Explanation: operator == must return bool.

3 An operator + declaration

Question
Vector operator +(____ other) => Vector(x + other.x, y + other.y);
Answer
Vector operator +(Vector other) => Vector(x + other.x, y + other.y);

Explanation: operator +(Vector other) adds two Vectors.

All lessons in Expert