Sobes.tech
Junior — Middle

Is it possible to use a data class with mutable properties as a key in a hash table?

sobes.tech AI

Answer from AI

Using a data class with mutable properties as a key in a hash table is not recommended. Keys in hash tables should be immutable because changing the properties of an object involved in hash code calculation or comparison can lead to loss of access to the element.

For example, if a property that affects hashCode or equals changes in a data class, the object will no longer be found in the hash table:

data class User(var id: Int, var name: String)

val map = hashMapOf<User, String>()
val user = User(1, "Alice")
map[user] = "Developer"

user.name = "Bob" // Changing the property

println(map[user]) // Might return null, as hashCode has changed

Therefore, it is better to use immutable objects or keys with immutable properties.

Is it possible to use a data class with mutable… - sobes.tech