https://kotlinlang.org logo
#getting-started
Title
# getting-started
v

v79

01/21/2022, 9:20 PM
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

Joffrey

01/21/2022, 9:24 PM
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

v79

01/21/2022, 9:25 PM
... 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

Joffrey

01/21/2022, 10:11 PM
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

v79

01/21/2022, 10:24 PM
Yes, absolutely, but I needed to exclude something from equality checks in this case.
j

Joffrey

01/21/2022, 11:45 PM
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

ephemient

01/22/2022, 9:13 AM
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)
2 Views