Solution: A mutability problem
Any operation that changes the name
property will make the code print false
. This is because mutableSetOf
uses hashCode
and equals
to check if an element is already in the set. When we add an element to the set, the set calculates its hash code and stores it. When we call contains
, the set calculates the hash code of the element we pass as an argument and compares it with the hash code of the element stored in the set. Since the hash code of name
is calculated based on the value of the name
property, changing the value of this property will change the hash code. Thus, the set will not be able to find the element we are looking for.
fun main() {
val set = mutableSetOf<Name>()
val name = Name("AAA")
set.add(name)
name.name = "BBB" // or any other text
println(set.contains(name)) // false
println(set.first() == name) // true
}
fun main() {
val set = mutableSetOf<Name>()
val name = Name("AAA")
set.add(name)
name.name = "BBB" // or any other text
println(set.contains(name)) // false
println(set.first() == name) // true
}
data class Name(var name: String)
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.