-
Notifications
You must be signed in to change notification settings - Fork 169
Recommend using runtimeType in hash_and_equals #1943
Conversation
> Using `is` in `operator ==` is usually wrong as it makes the `==` operator asymmetric. dart-lang/sdk#36004 (comment)
Thanks for your pull request. It looks like this may be your first contribution to a Google open source project (if not, look below for help). Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). 📝 Please visit https://cla.developers.google.com/ to sign. Once you've signed (or fixed any issues), please reply here with What to do if you already signed the CLAIndividual signers
Corporate signers
ℹ️ Googlers: Go here for more info. |
@googlebot I signed it! |
CLAs look good, thanks! ℹ️ Googlers: Go here for more info. |
I disagree with Hixie on this one. The use of The truth of the matter is that defining equality correctly is hard and there is no single right way to do so. If there were, the equality would be defined by the language rather than being something that developers had to define. If we want to update the docs to reflect that, then I think the better way to do so would be to have multiple different "good" examples to illustrate that there isn't a one-size-fits-all solution. As for this specific change, there's no reason to check both |
class Better {
final int value;
Better(this.value);
@override
bool operator ==(Object other){
if (other.runtimeType != runtimeType){
return false;
}
final Better typedOther = other;
return typedOther.runtimeType == runtimeType &&
typedOther.value == value;
}
@override
int get hashCode => value.hashCode;
}
/// We know this class will not be extended, and can therefore use `is` rather than `runtimeType`
class _Better {
final int value;
_Better(this.value);
@override
bool operator ==(Object other) => other is _Better && other.value == value;
@override
int get hashCode => value.hashCode;
} Seems a little long winded though |
Are all of the "it"s above referring to the use of |
@bwilkerson edited for clarification:
Would my proposed changes be preferable? |
@bwilkerson cleaning up old PRs – any more thoughts on this? |
No, no new thoughts. I still don't object to the change, but I think it would be better if the docs had more examples of good styles to point out to users there there isn't any single "right" way to write @pq Do you want to land this as-is? |
Thanks @pq! – |
> Using `is` in `operator ==` is usually wrong as it makes the `==` operator asymmetric. #36004 (comment)
Description
I based my early
==
overrides on thehash_and_equals
docs, so I'm sure others have done the same