How to get the name of a variable in Kotlin?

后端 未结 3 1609
孤城傲影
孤城傲影 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: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

提交回复
热议问题