Reputation: 1650
I am trying to create a function that can take any singleton object in, and print it's properties with values.
Sample code:
object MyObject {
val text = "Hello World"
}
inline fun <reified T: Any> printValues() = T::class
.declaredMemberProperties
.forEach {
println(it.name + "=" + it.value) // value doesn't exist
}
/* RUN */
fun main(args: Array<String>) {
printValues<MyObject>()
}
Is it possible in kotlin to retrieve the value from MyObject in some generic way like this?
Upvotes: 1
Views: 182
Reputation: 3105
How about something like this:
inline fun <reified T : Any> getObjectValues() = T::class
.declaredMemberProperties
.map { it.name to it.get(T::class.objectInstance!!) }
Basically what you need is to obtain an instance of T so that you can call get
Upvotes: 2