简体   繁体   中英

Do Enums in Dart have comparison operators?

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.

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 Enum s:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM