İs there a way to create an extension function for Any that returns that variables name?

Basically, i need something like this

fun Any.GetVariableNameAndValue() : String
{
    return "${this.reflection.name}: ${this}" // something like this
}

if the variable is directly passed without declaring it as a variable, the name should be null i guess? is there a way to do this?

You can have it operate on a reference instead:

import kotlin.reflect.*

class Foo {
   val foo = "hello"
}

var bar = 42

fun main() {
    val baz = "world"
    println(Foo()::foo.variableNameAndValue)
    println(::bar.variableNameAndValue)
    //println(::baz.variableNameAndValue) sadly doesn't work for local variables :(
}

val KProperty0<*>.variableNameAndValue get() = "$name: ${get()}"
1 Like