Skip to main content
The less-than-or-equal-to operator (<=) is a binary relational operator that evaluates the ordering of two operands. While conventionally used to return a boolean indicating numerical comparison, the operator’s specific logic, parameter types, and return type are determined by the implementation of the underlying method named <= on the left-hand operand.

Syntax

var result = leftOperand <= rightOperand;

Semantics and Desugaring

The expression a <= b is syntactic sugar for a method invocation on the left-hand operand (a). The Dart compiler resolves this expression using the following logic:
  1. Instance Method Resolution: The compiler looks for an instance method named <= on the class of a.
  2. Extension Method Resolution: If no instance member is found, the compiler looks for an applicable extension method named <= that accepts a as the receiver.
Conceptually, a <= b desugars to a.<=(b). However, a.<=(b) is not valid Dart syntax; the operator symbol must be used in the infix position.

Operator Declaration

To define or overload the <= operator, a class or extension must declare a method using the operator keyword followed by the symbol <=.
ReturnType operator <=(ParameterType other) {
  // Implementation
}
  • Method Name: The identifier of the method is <=. The operator keyword is a syntactic marker indicating that the method is an operator overload.
  • Parameter: The method accepts exactly one parameter, which corresponds to the right-hand operand.
  • Return Type: The Dart language specification permits any return type. However, the Dart Style Guide and standard library conventions dictate returning bool.

Standard Library Behavior

For the built-in num types (int and double), the operator adheres to IEEE 754 standards:
  • Finite Numbers: Returns true if the left operand is numerically less than or equal to the right operand.
  • Infinity:
    • -double.infinity <= value returns true for any value (except NaN).
    • value <= double.infinity returns true for any value (except NaN).
    • double.infinity <= value returns false for any finite value.
  • NaN: Any comparison involving double.nan returns false, including double.nan <= double.nan.

Example: Custom Implementation

The following example demonstrates overloading the <= operator in a custom class.
class Version {
  final int major;
  final int minor;

  const Version(this.major, this.minor);

  // Declares the method '<='
  bool operator <=(Version other) {
    if (major != other.major) {
      return major < other.major;
    }
    return minor <= other.minor;
  }
}

void main() {
  final v1 = Version(1, 0);
  final v2 = Version(1, 2);

  // Conceptually resolves to v1.<=(v2)
  print(v1 <= v2); // Output: true
}
Master Dart with Deep Grasping Methodology!Learn More