How to get the name of a variable in Kotlin?

As stated in the Kotlin documentation about Reflection:

val x = 1

fun main() {
    println(::x.get())
    println(::x.name) 
}

The expression ::x evaluates to a property object of type KProperty<Int>, which allows us to read its value using get() or retrieve the property name using the name property.


I think delegate properties is the solution to my problem:

class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
    return "$thisRef, thank you for delegating '${property.name}' to me!"
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
    println("$value has been assigned to '${property.name}' in $thisRef.")
  }
}

Credits go to: Roland
Source: https://kotlinlang.org/docs/reference/delegated-properties.html


Use memberProperties to get the names of the class attributes and others properties. For instance:

YourClass::class.memberProperties.map {
 println(it.name)
 println(it.returnType)
}