Skip to main content
The |= operator is the bitwise OR assignment operator. It performs a bitwise inclusive OR operation on the variable on the left-hand side (LHS) and the expression on the right-hand side (RHS), then assigns the resulting value back to the LHS variable.

Syntax

variable |= expression;

Semantics

The compound assignment expression a |= b is semantically equivalent to:
a = a | b;
The primary distinction is that in the compound form a |= b, the LHS operand a is evaluated only once.

Bitwise Logic

When applied to integer types, the operator processes operands at the binary level. It compares corresponding bits of both operands:
  • If either bit is 1, the resulting bit is 1.
  • If both bits are 0, the resulting bit is 0.
Truth Table:
Bit ABit BResult (A | B)
000
011
101
111

Supported Types

The |= operator is applicable to any type that defines the bitwise OR operator (|).
  • Core Types: Dart supports this operator natively for int and BigInt.
  • Custom Types: User-defined classes can support |= by overloading the | operator.
  • Type Safety: The return type of the | operation must be assignable to the type of the LHS variable.

Example: Integer Mutation

The following example demonstrates the mutation of an int variable using the |= operator.
void main() {
  int a = 5;  // Binary: 0101
  int b = 3;  // Binary: 0011

  // Operation: 0101 | 0011
  // Result:    0111 (Decimal 7)
  a |= b;

  print(a); // Output: 7
}

Operator Overloading

Dart does not allow explicit overloading of the |= operator itself. Instead, a class must overload the standard bitwise OR operator (|). If a class defines operator |, Dart automatically enables the |= syntax for that class.
class Flags {
  final int value;
  const Flags(this.value);

  // Overloading the bitwise OR operator
  Flags operator |(Flags other) {
    return Flags(this.value | other.value);
  }
}

void main() {
  var f1 = Flags(1); // Binary 01
  var f2 = Flags(2); // Binary 10
  
  // Uses the custom | operator and reassigns f1
  f1 |= f2; 
  
  print(f1.value); // Output: 3 (Binary 11)
}
Master Dart with Deep Grasping Methodology!Learn More