How to get the name of a variable in Kotlin?

后端 未结 3 1606
孤城傲影
孤城傲影 2020-12-20 19:55

I have a Kotlin class in my application with a lot of attributes, what I want to build is a method that stores the variable name in a dictionary. The dictionary looks like t

3条回答
  •  北海茫月
    2020-12-20 20:09

    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, which allows us to read its value using get() or retrieve the property name using the name property.

提交回复
热议问题