Do Enums in Dart have comparison operators?

Viewed 1315

I come from a Kotlin background and I used to the fact that enums there implements Comparable, which allows me do something like below:

Given a enum

enum class Fruit{
  APPLE,
  BANANA,
  ORANGE,
}

I could use the operators <, >, <= or >=, to compare any occurrence of this enum, like:

APPLE < BANANA -> true
ORANGE < BANANA -> false

I wonder if dart has the same by default or if I have to define custom operators to any enum I might need that.

3 Answers

As explained in other comments, you can also create your own operator and use it.

Try the code below to see how to handle it without creating an operator.

enum Fruit{
  APPLE,
  BANANA,
  ORANGE,
}

void main() {

  print(Fruit.APPLE.index == 0);
  print(Fruit.BANANA.index == 1);
  print(Fruit.ORANGE.index == 2);
  
  if( Fruit.APPLE.index < Fruit.BANANA.index ){
    // Write your code here
    print("Example");
  }
  
}

result

true
true
true
Example

It's easy to check Enum documentation or try it yourself to see that Enum classes do not provide operator <, operator >, etc.

Dart 2.15 does add an Enum.compareByIndex method, and you also can add extension methods to Enums:

extension EnumComparisonOperators on Enum {
  bool operator <(Enum other) {
    return index < other.index;
  }

  bool operator <=(Enum other) {
    return index <= other.index;
  }

  bool operator >(Enum other) {
    return index > other.index;
  }

  bool operator >=(Enum other) {
    return index >= other.index;
  }
}

Since 2.15, statically:

compareByIndex<T extends Enum>(T value1, T value2) → int
    Compares two enum values by their index. [...]
    @Since("2.15")
compareByName<T extends Enum>(T value1, T value2) → int
    Compares enum values by name. [...]
    @Since("2.15")

https://api.dart.dev/stable/2.16.1/dart-core/Enum-class.html

Related