在kotlin中与python id等价的是什么?



在python中,您可以通过id(object):

为任何对象获得唯一的数字ID:
person = Person()
person_id = id(person)

Kotlin中的等效函数是什么?

Kotlin中的类不会自动拥有唯一的ID。正如评论中提到的,你可以得到identityHashCode。它不能保证唯一,但在实践中,如果您只是使用它来比较日志中的项目,它可能是足够的。

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

如果您需要唯一的id,您可以在构造时使用伴随对象中的计数器分配它们。

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

或者,如果您在JVM上,您可以使用UUID类在实例化时为每个类生成一个统计上唯一的ID,但是这对于日志记录可能不是很有用。

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

最新更新