Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 61 ยท Classes and Object-Oriented Dart

Operator Overloading, ==, hashCode and toString

Learn how to overload operators in Dart, follow the equality contract with == and hashCode, implement Comparable and write a useful toString for your classes.

When you write a + b, a == b or a[0], Dart calls a method. Operators are ordinary instance methods with special names, so your own classes can define them. A Vector can support +, a Money can support <, and a Grid can support grid[row].

Most classes should do three things well even if they define no arithmetic at all: compare for equality in a meaningful way, produce a matching hashCode, and print something readable with toString. Get those wrong and objects vanish from sets, lookups in maps fail and debug output is useless. This lesson covers the operators, the equality contract and Comparable. The Dart snippets are read-only, and the runnable examples are TypeScript stand-ins.

Overloading operators

You define an operator with the operator keyword followed by the symbol:

DART
class Vector {
  const Vector(this.x, this.y);
  final double x;
  final double y;

  Vector operator +(Vector other) => Vector(x + other.x, y + other.y);
  Vector operator -(Vector other) => Vector(x - other.x, y - other.y);
  Vector operator *(double factor) => Vector(x * factor, y * factor);
  Vector operator -() => Vector(-x, -y);   // unary minus

  @override
  String toString() => 'Vector($x, $y)';
}

void main() {
  const a = Vector(1, 2);
  const b = Vector(3, 4);
  print(a + b);     // Vector(4.0, 6.0)
  print(b * 2);     // Vector(6.0, 8.0)
  print(-a);        // Vector(-1.0, -2.0)
}

The operators you can overload are +, - (binary and unary), *, /, ~/, %, <, >, <=, >=, ==, [], []=, ~, &, |, ^, <<, >> and >>>. You cannot overload &&, ||, !, ?:, ??, ., ?., .., != (it is always the negation of ==), or the assignment operators. Compound forms such as += and ++ come for free from +: a += b means a = a + b.

The index operators let a class behave like a collection:

DART
class Grid {
  Grid(this.width, this.height) : _cells = List.filled(width * height, 0);
  final int width;
  final int height;
  final List<int> _cells;

  int operator [](int index) => _cells[index];
  void operator []=(int index, int value) => _cells[index] = value;
}

void main() {
  final grid = Grid(3, 2);
  grid[4] = 7;
  print(grid[4]);   // 7
}

Restraint matters. Overload an operator only when its meaning is obvious to every reader. Vector + Vector is clear; user + order is not. If you need to explain what an operator does, a named method is better.

The equality contract

By default, == compares identity: two objects are equal only if they are the very same object. For value-like classes that is not what you want:

DART
class Point {
  const Point(this.x, this.y);
  final int x;
  final int y;
}

void main() {
  print(const Point(1, 2) == const Point(1, 2));  // true (canonicalized constants)
  print(Point(1, 2) == Point(1, 2));              // false: two different objects
}

To make equality depend on values, override == and hashCode together. Collections such as Set and Map use hashCode first to find a bucket and then == to confirm a match, so they must agree. The contract:

  1. If a == b, then a.hashCode == b.hashCode.
  2. == is reflexive, symmetric and transitive.
  3. hashCode is stable while the fields that take part in == do not change.
DART
class Point {
  const Point(this.x, this.y);
  final int x;
  final int y;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Point && other.runtimeType == runtimeType && other.x == x && other.y == y;

  @override
  int get hashCode => Object.hash(x, y);

  @override
  String toString() => 'Point($x, $y)';
}

void main() {
  print(Point(1, 2) == Point(1, 2));          // true
  final seen = {Point(1, 2), Point(1, 2), Point(3, 4)};
  print(seen.length);                          // 2
}

Four details deserve attention. The parameter of == is typed Object (not Point), because it must accept anything. The identical check is a cheap shortcut. The runtimeType comparison keeps subclasses from being equal to their parents by accident, which would break symmetry. And Object.hash(a, b, ...) combines the field hashes well, so you do not need to invent a formula. For a list of values use Object.hashAll(list).

Never include mutable fields in hashCode unless you promise not to mutate the object while it sits in a set or map. If a field changes after insertion, the object sits in the wrong bucket and later lookups fail. That is why value classes are best made immutable, with final fields.

flowchart TD
    Q["set.contains(p)"] --> H["Compute p.hashCode"]
    H --> B["Find the bucket"]
    B --> E{"Any element with<br/>== p in the bucket?"}
    E -->|yes| T["true"]
    E -->|no| F["false"]

Sets and maps use hashCode to pick a bucket and == to confirm the match, so the two must agree.

For plain data holders, writing this by hand is tedious. Records already provide value equality (see Records), and packages such as equatable or the code generator freezed generate the boilerplate. Know the manual version first, because you will meet it constantly.

TypeScript Value equality and operators (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Implementing Comparable

Operators like < and > are rarely defined directly. The idiomatic way to give a class an ordering is to implement Comparable<T>, which has one method, compareTo. It returns a negative number if this comes first, zero if they are equal in order, and a positive number if this comes after.

DART
class Version implements Comparable<Version> {
  const Version(this.major, this.minor);
  final int major;
  final int minor;

  @override
  int compareTo(Version other) {
    final byMajor = major.compareTo(other.major);
    return byMajor != 0 ? byMajor : minor.compareTo(other.minor);
  }

  bool operator <(Version other) => compareTo(other) < 0;
  bool operator >(Version other) => compareTo(other) > 0;

  @override
  String toString() => '$major.$minor';
}

void main() {
  final versions = [Version(2, 1), Version(1, 9), Version(2, 0)];
  versions.sort();                  // uses compareTo
  print(versions);                  // [1.9, 2.0, 2.1]
}

Once the class is Comparable, list.sort() works with no argument, and generic code that accepts Comparable values can order your objects too. Keep compareTo consistent with == where you can: if compareTo returns zero, the objects should usually be equal.

Writing a useful toString

print(object) and string interpolation call toString(). The default prints Instance of 'Point', which tells you nothing. Override it to show the type and the important fields, in a form you could paste into a bug report: Point(1, 2). Do not put secrets such as passwords into toString, because logs and error messages will include them. For collections of objects, a good toString makes print(list) readable at a glance.

TypeScript Sorting with a comparison method (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if a class overrides == but not hashCode?

    Sets and maps use hashCode first. If equal objects return different hash codes, lookups can miss them and duplicates can appear.
  2. 2. Which operator can NOT be overloaded in Dart?

    The logical operators && and || cannot be overloaded, and != is always the negation of ==.
  3. 3. How does a += b work for a class that defines only +?

    Compound assignment is built from the underlying operator, so defining + gives you += for free.
  4. 4. What does compareTo return when this should be sorted before other?

    compareTo returns negative for before, zero for equal order and positive for after.
  5. 5. Why should the fields used in hashCode be final?

    If a field that feeds hashCode changes while the object is inside a Set or Map, the object is stored under the old hash and can no longer be found.

Summary

  • Operators are instance methods declared with operator; overload them only when the meaning is obvious.
  • Override == and hashCode together, use Object.hash, and keep value classes immutable.
  • Implement Comparable<T> for ordering so that sort() just works.
  • Write a toString that shows the type and key fields, but never secrets.
  • Records, equatable and code generators remove the boilerplate for plain data classes.

Next, learn about shared state and constants in Static Members, Constants and Callable Classes.