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
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 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
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)
}