Skip to main content
The - symbol functions as two distinct operators in Dart: the binary subtraction operator and the unary negation operator. These operators differ in arity, precedence, and the underlying instance method selector to which they resolve.

Binary Subtraction Operator

The binary - operator performs subtraction between two operands. It is left-associative and resolves to the instance method named -. Syntax
expression1 - expression2
Semantics The expression a - b is semantically equivalent to invoking the operator method - on the instance a with the argument b.

Unary Negation Operator

The unary - operator is a prefix operator that negates the value of the operand. It resolves to the special instance method selector unary-. Syntax
-expression
Semantics The expression -a is semantically equivalent to invoking the operator method corresponding to the selector unary- on the instance a with no arguments.

Operator Declaration

Classes define the behavior for these operators using the operator keyword. Although the unary operator resolves to the unary- selector, both operators are declared using the operator - syntax. The Dart compiler distinguishes between them based on the number of parameters defined in the declaration. Binary Declaration To support binary subtraction, declare operator - with exactly one parameter.
class Vector {
  final int x, y;
  Vector(this.x, this.y);

  // Binary subtraction: Vector - Vector
  // Selector: -
  Vector operator -(Vector other) {
    return Vector(x - other.x, y - other.y);
  }
}
Unary Declaration To support unary negation, declare operator - with zero parameters.
class Vector {
  final int x, y;
  Vector(this.x, this.y);

  // Unary negation: -Vector
  // Selector: unary-
  Vector operator -() {
    return Vector(-x, -y);
  }
}

Precedence and Associativity

The two operators function at different levels of the Dart grammar precedence table:
  1. Unary -: Has high precedence (level 15), binding tighter than multiplicative (*, /) or additive (+, -) operators.
  2. Binary -: Has additive precedence (level 13), is equal in precedence to the binary + operator, and is evaluated left-to-right.
Evaluation Example
// 1. Unary -b is evaluated first (Precedence 15).
// 2. a * (-b) is evaluated next (Multiplicative, Precedence 14).
// 3. (result) - c is evaluated last (Additive, Precedence 13).
var result = a * -b - c;
Master Dart with Deep Grasping Methodology!Learn More