freezed icon indicating copy to clipboard operation
freezed copied to clipboard

Unfreezed class without ==/hashcode implementation

Open bruzzers opened this issue 2 years ago • 1 comments

Hi, thank you for the plugin, is brilliant. But I have a question, why are mutable and unfreezed classes without ==/hashcode implementation? it's such strange cause mutable classes are where is most important to check two items are different or equals.

Thank you, hope to see this improvement sono.

bruzzers avatar Jul 20 '22 15:07 bruzzers

By definition, ==/hashCode should not be overridden on mutable classes.

An ==/hashCode override on mutable classes would violate the contract of those methods and break features such as Map/Set, leading to various problems.

rrousselGit avatar Jul 20 '22 16:07 rrousselGit

Closing as this is expected

rrousselGit avatar Sep 27 '22 14:09 rrousselGit

I ran into this problem today and just thought I'd add a bit more info in case others stumble across it too.

Initially, not generating ==/hashCode didn't make any sense to me... after all, just because an object is declared as mutable, it doesn't mean that we don't want to be able to compare them.

However, after a bit of googling, I found this page that talks about how a mutable instance's values changing could end up changing the hashCode which, as @rrousselGit says above, could cause problems for Map and Set. Fair enough.

Here's the thing though... we often still need to compare these objects, however, any generated hashCode implementation would almost certainly get it wrong because Freezed won't know what the stable key is.

The secret is to write your own ==/hashCode implementations. Care still needs to be taken, though, because of the problem around stable hash codes... in my specific case, one of my attributes is indeed an immutable identifier so the solution for me is to hand-write my own ==/hashCode functions that use that stable object.

edwardaux avatar Oct 13 '22 18:10 edwardaux