Skip to main content
The | operator in Dart functions in two distinct contexts: as the Bitwise Inclusive OR operator for integers and as the Logical-OR combinator for pattern matching.

1. Bitwise Inclusive OR (Integers)

When applied to operands of type int, the | operator performs a bitwise inclusive OR operation on the two’s complement binary representation of the numbers. It compares each bit of the left operand to the corresponding bit of the right operand. The resulting bit is set to 1 if either or both operands have a 1 at that position; otherwise, it is 0. Syntax:
int result = integerExpression1 | integerExpression2;
Behavior:
  • Arity: Binary.
  • Operand Type: int.
  • Return Type: int.
Example:
void main() {
  int x = 5;      // Binary: 0101
  int y = 3;      // Binary: 0011
  
  // 0101
  // 0011
  // -
  // 0111 (Decimal: 7)
  int result = x | y; 
  
  print(result); // Output: 7
}

2. Logical-OR Pattern (Pattern Matching)

In the context of Dart patterns (introduced in Dart 3.0), the | operator acts as a disjunctive pattern combinator. It allows a pattern to match if any of the sub-patterns match the value being tested. This operator is valid within pattern matching contexts such as switch expressions, switch statements, and if-case statements. Syntax:
case subPatternA | subPatternB:
Constraints:
  • Variable Binding: If the pattern binds variables, every sub-pattern joined by | must bind the exact same set of variables with the same types. This ensures that regardless of which branch matches, the variables are definitely assigned.
Example:
void checkStatus(int code) {
  switch (code) {
    // Matches if code is exactly 200 OR exactly 201
    case 200 | 201:
      print('Success');
    default:
      print('Unknown');
  }
}
Master Dart with Deep Grasping Methodology!Learn More