Home > other >  Why is my kotlin hash set not adding elements
Why is my kotlin hash set not adding elements

Time:07-23

I am new to kotlin and I want to make an abstract/open class or interface, something that can be implemented by other classes. Let's call it Test. Now Test needs to have a HashSet (the docs say it requires less memory than a normal set) that every derived class will implement and fill with its own values.

interface Test {
    val players: HashSet<String>
}
class Supa: Test {
    override val players = hashSetOf<String>()
    fun later() {
        players.add("new player")
    }
}
fun main() {
    Supa().later()
    println(Supa().players)
    
}

The above will output []. It seems that for some reason players doesn't get updated. After playing around in the kotlin playground I found out that if I print players from inside later() it will show the added element. Maybe it creates a new instance of player that exists in the scope of the function?? Could someone please show me how I can make an abstract hashSet that the derived class can override and fill with values that stay in the set?

CodePudding user response:

The problem here is that you create two separate instances of Supa. You invoke later() on one of them and then print players of another one. Each Supa() creates a new instance.

You need to store Supa instance inside a variable and use it in both places:

val supa = Supa()
supa.later()
println(supa.players)

This isn't really specific to Kotlin. Your code would work the same in other languages as well.

  • Related