Question above. I have already tried this: https://stackoverflow.com/a/24305983/16707725 but it doesn't work for me. Classes seem not to be able to memorize values.
fun main() {
val worker = Worker("Frank")
val worker2 = Worker("Elvis")
println(worker.id)
println(worker2.id)
}
class Worker(val name: String) {
private val count: AtomicInteger = AtomicInteger(1)
var id = count.incrementAndGet()
}
Your property is a member of the class, so there is a new count
property created and new AtomicInteger assigned for each instance of Worker
. Your linked Java example is using a static field for the count
so there is only one for all instances of the class. There are two ways to do this in Kotlin.
private val count: AtomicInteger = AtomicInteger(1)
class Worker(val name: String) {
val id = count.incrementAndGet()
}
object
. A companion object
is the typical choice for something like this. The object
is shared by all instances of the class.class Worker(val name: String) {
companion object {
private val count: AtomicInteger = AtomicInteger(1)
}
val id = count.incrementAndGet()
}