Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get address of an object in Kotlin?

Tags:

kotlin

Simple question but I didn't see any answers on the internet. So, how can I get address of an object in Kotlin?

like image 537
mr.icetea Avatar asked Jan 08 '19 10:01

mr.icetea


2 Answers

To identify an object during debugging, use System.identityHashCode().

The address of an object can't be obtained on Kotlin/JVM, and it can also change as GC runs, so it can't be used to identify an object.

like image 66
yole Avatar answered Sep 30 '22 07:09

yole


Kotlin in the JVM does not support pointers and so (apart from some jiggery-pokery with the sun.misc.Unsafe class) there is no way to obtain a variable's address.

However, Kotlin/Native (at least back in January 2018) does support pointers to enable it to interoperate with C code. The following program shows how to obtain the address of a variable which has been allocated on the native heap. It does not appear to be possible to allocate a variable at a particular address.

// Kotlin Native v0.5

import kotlinx.cinterop.*

fun main(args: Array<String>) {
    val intVar = nativeHeap.alloc<IntVar>()
    intVar.value = 42
    with(intVar) { println("Value is $value, address is $rawPtr") }
    nativeHeap.free(intVar)
}

results in:

Value is 42, address is 0xc149f0
like image 23
Yolgie Avatar answered Sep 30 '22 08:09

Yolgie