Skip to main content
The &= operator is a compound assignment operator that performs a bitwise or logical AND operation on the left-hand operand (variable) and the right-hand operand (expression), assigning the result back to the left-hand operand.

Syntax and Semantics

The expression a &= b is syntactically equivalent to a = a & b, with the specific semantic distinction that the left-hand operand a is evaluated exactly once. If the left-hand operand is an expression with side effects (such as a list access with an incrementing index), those side effects occur only once during the operation.
void main() {
  var list = [12];
  var i = 0;

  // The index 'i' is incremented only once.
  // Equivalent logic: list[0] = list[0] & 10; i++;
  list[i++] &= 10;

  print(list); // [8]
  print(i);    // 1
}

Supported Types

The operator functions on any type that defines the & operator. In the Dart core libraries, this includes:
  • int
  • BigInt
  • bool

Bitwise AND (Integers)

When applied to int or BigInt types, &= performs a bitwise AND operation on the binary representation of the operands. The resulting bit is set to 1 only if the corresponding bits of both operands are 1.
void main() {
  int flags = 12; // Binary: 1100
  int mask = 10;  // Binary: 1010

  // Operation:
  //   1100
  // & 1010
  // ---
  //   1000 (Decimal: 8)
  
  flags &= mask; 

  print(flags); // Output: 8
}

Logical AND (Booleans)

When applied to bool types, &= performs an eager logical AND. Unlike the short-circuit assignment operator (&&=), the &= operator always evaluates the right-hand operand because the underlying & operator on booleans is non-short-circuiting.
  1. If both operands are true, the variable is assigned true.
  2. If either operand is false, the variable is assigned false.
void main() {
  bool isEnabled = true;
  
  // The right-hand side is evaluated regardless of the value of isEnabled.
  isEnabled &= (1 > 2); 

  print(isEnabled); // Output: false
}

Operator Overloading Requirements

The &= operator can be used with custom types if the class of the left-hand operand defines operator &. The usage is subject to the following type constraints:
  1. Parameter Type: The right-hand operand must be of a type accepted by the defined operator &.
  2. Return Type: The return type of the operator & must be assignable to the type of the left-hand variable.
class CustomBit {
  final int value;
  CustomBit(this.value);

  // The operator takes an int and returns a CustomBit.
  CustomBit operator &(int other) {
    return CustomBit(value & other);
  }
}

void main() {
  var cb = CustomBit(12);
  
  // Valid: 
  // 1. cb.operator&(10) is called.
  // 2. The result (CustomBit) is assigned back to cb.
  cb &= 10; 
}
Master Dart with Deep Grasping Methodology!Learn More