Junior — Middle
How can you implement custom behavior for comparison operators in Dart?
sobes.tech AI
Answer from AI
In Dart, to implement custom behavior for comparison operators, you can override the == operator and the compareTo method (if the class implements the Comparable interface).
Example of overriding the == operator and hashCode method for correct object comparison:
class Person {
final String name;
final int age;
Person(this.name, this.age);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Person && other.name == name && other.age == age;
}
@override
int get hashCode => name.hashCode ^ age.hashCode;
}
To sort objects, you can implement Comparable and the compareTo method:
class Person implements Comparable<Person> {
final String name;
final int age;
Person(this.name, this.age);
@override
int compareTo(Person other) {
return age.compareTo(other.age);
}
}
Thus, you define your own object comparison logic.