Does Kotlin's LinkedHashMap use reference identity...
# getting-started
v
Does Kotlin's LinkedHashMap use reference identity or equals() in its
get()
method? I have two different objects with the same values, and an overridden equals method which returns true. But as a key to hashmap, they don't match.
j
Have you also overridden
hashCode()
accordingly? 2 equal objects must have the same hashcode, that's the contract between both methods. Hashmaps rely on this by first checking hashcode and then using equals when searching for keys
v
... suddenly I feel dumb. Be right back!
I've been a professional Java dev for about 10 years but now I'm just a manager. Clearly I'm forgetting the basics!
😆 2
👏 1
j
Note that if you use Kotlin's data classes, they will have autogenerated hashcode and equals based on the properties declared in the primary constructor. It's usually easier this way
v
Yes, absolutely, but I needed to exclude something from equality checks in this case.
j
Then it may depend on your exact case, but just in case, you can exclude properties from the generated `equals`/`hashCode` if you declare them outside of the primary constructor (directly in the data class's body)
e
https://youtrack.jetbrains.com/issue/KT-40850 I think I'd be ok with a change to the language to allow
@Transient
or some other annotation to exclude a property from the auto-generated equals and hashCode (but that's clearly not what we have now)