How to get the name of a variable in Kotlin?

后端 未结 3 1594
孤城傲影
孤城傲影 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<Int>, which allows us to read its value using get() or retrieve the property name using the name property.

    0 讨论(0)
  • 2020-12-20 20:12

    I think delegate propperties are the sollution 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

    0 讨论(0)
  • 2020-12-20 20:16

    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)
    }
    
    0 讨论(0)
提交回复
热议问题