Skip to main content
The | operator in Dart serves as the bitwise inclusive OR operator for integers, a non-short-circuiting logical OR operator for booleans, and an overloadable operator for custom classes.

Integer Bitwise OR

When applied to int operands, the | operator evaluates the binary representations of both operands position by position. If at least one of the corresponding bits is 1, the resulting bit is 1. If both bits are 0, the resulting bit is 0. The operation returns an int. Truth Table:
  • 0 | 0 yields 0
  • 0 | 1 yields 1
  • 1 | 0 yields 1
  • 1 | 1 yields 1
Platform Constraints:
  • Dart Native (AOT/JIT): Bitwise operations are performed on 64-bit two’s complement integers.
  • Dart Web (compiled to JavaScript): Bitwise operations are truncated to 32-bit integers to align with JavaScript’s underlying bitwise semantics.
int a = 5; // Binary representation: ... 0101
int b = 3; // Binary representation: ... 0011

int result = a | b; 

print(result); // Outputs: 7 (Binary: ... 0111)

Boolean Non-Short-Circuiting OR

When applied to bool operands, the | operator performs a logical OR operation returning a bool. Unlike the standard logical OR operator (||), the | operator does not short-circuit. It strictly evaluates both the left and right expressions regardless of whether the left expression evaluates to true.
bool evaluateRight() {
  print('Right evaluated');
  return true;
}

void main() {
  // 'evaluateRight()' is executed even though the left operand is true.
  bool result = true | evaluateRight(); 
}

Operator Overloading

Dart supports operator overloading, allowing user-defined classes to implement the | operator. The parameter type and the return type are entirely dictated by the class definition.
class CustomValue {
  final int value;
  
  CustomValue(this.value);

  // Overriding the | operator
  CustomValue operator |(CustomValue other) {
    return CustomValue(this.value | other.value);
  }
}

void main() {
  CustomValue val1 = CustomValue(8);
  CustomValue val2 = CustomValue(4);
  
  CustomValue result = val1 | val2;
}

Compound Assignment

The | operator can be combined with the assignment operator (=) to mutate a variable in place using the |= syntax. The variable being assigned to must be mutable (not final or const).
int value = 5;
value |= 3; // Strictly equivalent to: value = value | 3;

bool flag = false;
flag |= true; // Strictly equivalent to: flag = flag | true;
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More