Skip to main content
The *= operator is a compound assignment operator that multiplies the current value of the left operand by the value of the right operand, and subsequently assigns the resulting product back to the left operand.

Syntax

leftOperand *= rightOperand;

Technical Mechanics

  • Evaluation Order: Dart evaluates expressions strictly left-to-right. The left operand (the receiver/target) is evaluated first, followed by the right operand. The multiplication is then performed, and the result is assigned back to the left operand.
  • Single Evaluation: The compound assignment operator evaluates the leftOperand exactly once. This makes leftOperand *= rightOperand technically distinct from the expanded form leftOperand = leftOperand * rightOperand when the left operand contains side effects. For example, list[i++] *= 2 increments i only once, whereas list[i++] = list[i++] * 2 would evaluate the left operand twice, incrementing i twice.
  • Mutability: The left operand must be a mutable reference. It cannot be declared as const or final.
  • Operator Overloading: The *= operator is not restricted to core numeric types. It functions by invoking the operator * method on the left operand. It can be used with any custom class that implements operator *.

Type Safety and Promotion Rules

Because Dart is statically typed, the result of the multiplication operation must be assignable to the declared type of the left operand. Numeric Types When using Dart’s core numeric types (int, double, num), type promotion dictates the following behaviors:
  • Integer Assignment: If both operands are integers, the result is an integer and safely assigns back to an int variable.
  • Double Assignment: If the left operand is a double, the right operand can be either an int or a double. The result will always be a double.
  • Compile-Time Type Errors: If the left operand is strictly typed as an int and the right operand is a double, the multiplication yields a double. Dart will not implicitly downcast a double to an int, resulting in a compile-time error.
int a = 5;
a *= 3; // Evaluates to 15. Type remains int.

double b = 2.5;
b *= 2; // Evaluates to 5.0. Type remains double.

int c = 4;
// c *= 1.5; // COMPILE ERROR: A value of type 'double' can't be assigned to a variable of type 'int'.
Custom Types When using *= with custom classes, the return type of the overloaded operator * must be assignable to the variable’s type, and the right operand must match the parameter type defined in the method signature.
class Vector {
  final int value;
  Vector(this.value);

  Vector operator *(int scalar) => Vector(value * scalar);
}

Vector v = Vector(2);
v *= 3; // Valid: Invokes `operator *` and assigns the resulting Vector(6) back to `v`.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More