compareWith method

Comparison compareWith(
  1. T other
)

Compares this value with another value of the same type.

Returns a Comparison enum indicating the relationship between this value and other.

This is a type-safe wrapper around Comparable.compareTo that converts the integer result to a meaningful enum value.

Parameters:

  • other: The value to compare this against.

Returns:

Example:

final comparison = 5.compareWith(3);
assert(comparison == Comparison.greater);

if (name.compareWith('Alice') == Comparison.less) {
  print('Name comes before Alice');
}

Implementation

Comparison compareWith(T other) {
  final result = compareTo(other);

  return switch (result) {
    < 0 => .less,
    == 0 => .equal,
    > 0 => .greater,
    _ => throw Exception('Impossible case'),
  };
}