Skip to main content
The subtraction assignment operator (-=) is a compound assignment operator that subtracts the value of the right-hand operand from the variable on the left-hand side and assigns the resulting difference back to the left-hand variable.

Syntax

variable -= expression;
This syntax is syntactic sugar for the following operation:
variable = variable - expression;

Operational Mechanics

  1. Evaluation: The expression on the right-hand side is evaluated.
  2. Operation: The - operator is invoked on the current value of variable with the evaluated result of expression as the argument.
  3. Assignment: The result of the subtraction is assigned to variable.

Type Constraints

  • Mutability: The variable on the left-hand side must be mutable. It cannot be declared as final or const.
  • Type Compatibility: The type of the variable must define the subtraction operator (operator -). Additionally, the return type of the subtraction operation must be a subtype of the variable’s declared type.

Examples

Standard Numeric Types Dart’s built-in int and double types support this operator natively.
int x = 10;
x -= 4; // x is now 6

double y = 5.5;
y -= 1.5; // y is now 4.0
Operator Overloading The -= operator functions on any class that overrides the - operator, provided the return type matches the variable type.
class Vector {
  final int x, y;
  Vector(this.x, this.y);

  // Define the subtraction operator
  Vector operator -(Vector other) => Vector(x - other.x, y - other.y);
}

void main() {
  var v1 = Vector(5, 5);
  final v2 = Vector(2, 1);

  // v1 = v1 - v2
  v1 -= v2; // v1 is now Vector(3, 4)
}
Master Dart with Deep Grasping Methodology!Learn More