article banner

Exercise: A mutability problem

What operation on name will make the following code print false?

fun main() { val set = mutableSetOf<Name>() val name = Name("AAA") set.add(name) // ??? println(set.contains(name)) // should print false println(set.first() == name) // should print true } data class Name(var name: String)

This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in effective/safe/NameAndSet.kt. You can find there starting code.

Once you are done with the exercise, you can check your solution here.

Playground

fun main() { val set = mutableSetOf<Name>() val name = Name("AAA") set.add(name) // ??? println(set.contains(name)) // should print false println(set.first() == name) // should print true } data class Name(var name: String)