Search code examples
classkotlinpropertiesinstanceauto-increment

Each instance of class 'Worker' should have an own id, starting at 1 and get incremented everytime (1, 2, 3 and so on)


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()
}

Solution

  • 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.

    1. Top level property (defined outside the class) in the same file.
    private val count: AtomicInteger = AtomicInteger(1)
    
    class Worker(val name: String) {
        val id = count.incrementAndGet()
    }
    
    1. Put it in an 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()
    }