Home > other >  Do Enums in Dart have comparison operators?
Do Enums in Dart have comparison operators?

Time:01-12

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.

CodePudding user response:

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;
  }
}

CodePudding user response:

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
  •  Tags:  
  • Related