Skip to main content
The unary prefix negation operator (-) is a syntactic mechanism that inverts the sign of a numeric operand or executes custom logic defined by the operator unary- instance method. It functions as syntactic sugar, resolving to a specific method call on the target object with an arity of zero.

Syntax

-expression

Operator Semantics

When the Dart compiler processes a prefix - before an identifier or expression, it resolves the operation to the instance method declared as operator unary-. Given an object x, the expression -x triggers the logic defined in operator unary-. While the method is declared using the operator keyword, it cannot be invoked explicitly using dot notation (e.g., x.operator unary-() is a syntax error). The invocation is strictly implicit via the prefix syntax.

Precedence and Associativity

The unary negation operator possesses higher precedence than multiplicative (*, /, ~/, %) and additive (+, -) binary operators. It associates from right to left.
// Parsed as -(x) * y, not -(x * y)
var result = -x * y; 

Implementation in Custom Classes

To support the -x syntax in a user-defined class, the class must explicitly override the unary- operator. The method signature must not accept arguments.
class Vector {
  final int x;
  final int y;

  const Vector(this.x, this.y);

  // Declaration of the unary negation operator
  Vector operator unary-() {
    return Vector(-x, -y);
  }
}

void main() {
  final v = Vector(10, 20);
  
  // Implicitly invokes the logic defined in operator unary-
  final negativeV = -v; 
}

Distinction from Binary Subtraction

Dart distinguishes between negation and subtraction based on the operator’s position and the number of operands. These operations map to distinct method signatures within a class definition:
  • Unary Negation (-a): Maps to operator unary-(). It requires zero parameters.
  • Binary Subtraction (a - b): Maps to operator -(other). It requires one parameter.
These methods are independent; a class may implement one, both, or neither, and they may return different types.
Master Dart with Deep Grasping Methodology!Learn More