Book Image

DART Essentials

Book Image

DART Essentials

Overview of this book

Table of Contents (16 chapters)
Dart Essentials
About the Author
About the Reviewers

Operator overloading and mixins

We'll take a look at two more Dart features that are useful in some situations but aren't crucial when using Dart, and you'll probably not use them on a daily basis.

Operator overloading

Dart lets us overload its default behavior when using standard operators such as ==, +, -, [], or []=. A typical use case is when using 2D/3D vectors:

class Vector {
  int x, y;
  Vector(this.x, this.y);
  operator ==(Vector v) => this.x == v.x && this.y == v.y;
  operator  +(Vector v) => new Vector(this.x + v.x, this.y + v.y);
  operator  -(Vector v) => new Vector(this.x - v.x, this.y - v.y);

We can use unit testing to check whether operators work as expected:

var v1 = new Vector(5, 3);
var v2 = new Vector(7, 2);

Vector v3 = v1 + v2;
expect(v3.x, 12);
expect(v3.y, 5);

expect((v1 - v2) == new Vector(-2, 1), isTrue);

var v6 = new Vector(3, 5);
expect(v1 == v6, isFalse);

Unlike JavaScript, there's no === operator (three equal signs) in Dart that compares variables...