Mei Zhang
Mei Zhang

Reputation: 1714

what is the equivalent of python id in kotlin?

In python you can get a unique numeric ID for any object via id(object):

person = Person()
person_id = id(person)

What is the equivalent function in Kotlin?

Upvotes: 1

Views: 153

Answers (1)

Tenfour04
Tenfour04

Reputation: 93789

Classes in Kotlin do not automatically have a unique ID. As mentioned in the comments, you can get the identityHashCode. It is not guaranteed unique, but in practice if you are just using it to compare items in a log, it is probably sufficient.

class Person() {
    val id: Int get() = System.identityHashCode(this)
}

If you need unique IDs, you could assign them at construction time using a counter in a companion object.

class Person() {
    val id: Long = nextId

    companion object {
        private var nextId: Long = 0L
            get() = synchronized(this) { ++field }
            set(_) = error("unsupported")
    }
}

// Or simpler on JVM:
class Person() {
    val id: Long = idCounter.getAndIncrement()

    companion object {
        private val idCounter = AtomicLong(1L)
    }
}

Or if you are on JVM, you can use the UUID class to generate a statistically unique ID for each class as it is instantiated, but this is probably not very useful just for logging.

class Person() {
    val id = UUID.randomUUID()
}

Upvotes: 1

Related Questions