Skip to content

Instantly share code, notes, and snippets.

@odiak
Created June 19, 2017 11:56
Show Gist options
  • Save odiak/a34235accb25779094836b6e02f0cfd1 to your computer and use it in GitHub Desktop.
Save odiak/a34235accb25779094836b6e02f0cfd1 to your computer and use it in GitHub Desktop.
import kotlin.reflect.KClass
import kotlin.reflect.full.memberProperties
open class A {
val a = "xxxx"
var b = 12
}
class B : A() {
val c: String? = null
}
fun <T : Any> T.toMap(): Map<String, String?> {
@Suppress("unchecked_cast")
val klass: KClass<T> = this::class as KClass<T>
val map = mutableMapOf<String, String?>()
klass.memberProperties.forEach { p ->
map[p.name] = p(this)?.toString()
}
return map
}
fun main(args: Array<String>) {
val b = B()
println(b.toMap()) // {c=null, a=xxxx, b=12}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment