I cannot redeclare the "==" operator inside an extension type
extension type Compare(List<int> types) {
@redeclare
bool operator ==(List<int> other) =>true;
}
I get these errors:
Extension types can't declare members with the same name as a member declared by 'Object'. Try specifying a different name for the member
and this
The method doesn't redeclare a method declared in a superinterface. Try updating this member to match a declaration in a superinterface, or removing the redeclare annotation
Is there a way to redeclare it inside an extension type?
The analyzer produces this diagnostic when an extension declaration declares a member with the same name as a member declared in the class Object. Such a member can never be used because the member in Object is always found first.
Example:
The following code produces this diagnostic because toString
is defined by Object
:
extension E on String {
String toString() => this;
}
Since members of the Object
class can't be overridden in an extension
, you should use another name for your desired functionality.
extension ListComparison on List<int>{
bool equals (List<int> other){
if(length != other.length)
return false;
for(int i = 0 ; i < length; i++){
if(this[i] != other[i])
return false;
}
return true;
}
// you can't overload == operator in extensions, reserved by object
}
print([1,2,3].equals([1,2,3])); // true
print([1,2,3].equals([1,2,2])); // false
Hope it helps you.