Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A relational pattern compares a matched value against a given constant using standard relational operators. It evaluates to true if the boolean result of applying the operator between the matched value and the constant expression is true.

Syntax

<relational_operator> <constant_expression>
The <relational_operator> can be any of the following: ==, !=, <, >, <=, or >=. The <constant_expression> must evaluate to a compile-time constant.

Mechanics and Behavior

  1. Constant Requirement: The operand on the right side of the relational operator must be a compile-time constant. Variables evaluated at runtime are not permitted.
  2. Static Type Safety: The Dart analyzer statically verifies that the relational operator is defined for the static type of the matched value. If the matched value is of a type that does not implement the specified operator, a compile-time error occurs.
  3. Evaluation Order: When matching a value v against a relational pattern op c, the expression evaluates exactly as v op c.
  4. Exhaustiveness Checking: Dart’s exhaustiveness checker does not reason about the mathematical completeness of relational patterns. Even if a set of relational patterns logically covers all possible values (e.g., < 0, == 0, > 0), the compiler cannot deduce this. A default case (such as _) is strictly required in switch expressions utilizing relational patterns to prevent a non_exhaustive_switch_expression compile-time error.

Code Examples

In a Switch Expression:
String evaluateMagnitude(int value) => switch (value) {
  < 0  => 'Negative',
  == 0 => 'Zero',
  > 0  => 'Positive',
  _    => 'Unreachable', // Required because the compiler does not evaluate relational logic for exhaustiveness
};
Combined with Logical Patterns: Relational patterns are frequently combined with logical AND (&&) or logical OR (||) patterns to define bounded ranges.
bool isValidPercentage(int value) {
  return switch (value) {
    >= 0 && <= 100 => true,
    _ => false,
  };
}
In an if-case Statement:
void checkThreshold(double temperature) {
  if (temperature case >= 100.0) {
    print('Threshold met.');
  }
}

Operator Overloading

Relational patterns respect custom operator overloading. If a user-defined class overrides a relational operator (such as operator >), a relational pattern can be applied to instances of that class, provided the right-hand operand is a valid constant of the expected type.
class Measurement {
  final int value;
  const Measurement(this.value);

  bool operator >(Measurement other) => this.value > other.value;
}

void compareMeasurements(Measurement m) {
  // The right-hand side must be a const instantiation
  if (m case > const Measurement(50)) {
    print('Exceeds threshold');
  }
}
Master Dart with Deep Grasping Methodology!Learn More