Reputation: 1286
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.
Upvotes: 8
Views: 7770
Reputation: 21
If you want to define your own order, then this is a simple and compact solution:
enum Fruit {
APPLE, // index 0
BANANA, // index 1
ORANGE; // index 2
bool operator >(Similarity other) => index > other.index;
bool operator <(Similarity other) => index < other.index;
bool operator >=(Similarity other) => index >= other.index;
bool operator <=(Similarity other) => index <= other.index;
}
Note that the order is reversed. ORANGE > BANANA = true
If you want to compare the words APPLE, BANANA and ORANGE instead, then you can use this:
enum Fruit {
APPLE,
BANANA,
ORANGE;
bool operator >(Similarity other) => toString().compareTo(other.toString()) > 0;
bool operator <(Similarity other) => toString().compareTo(other.toString()) < 0;
bool operator >=(Similarity other) => toString().compareTo(other.toString()) >= 0;
bool operator <=(Similarity other) => toString().compareTo(other.toString()) <= 0;
}
Upvotes: 2
Reputation: 90155
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<T extends Enum> on T {
bool operator <(T other) {
return index < other.index;
}
bool operator <=(T other) {
return index <= other.index;
}
bool operator >(T other) {
return index > other.index;
}
bool operator >=(T other) {
return index >= other.index;
}
}
Upvotes: 7
Reputation: 1571
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
Upvotes: 1
Reputation: 49
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
Upvotes: 2