Skip to content

Instantly share code, notes, and snippets.

@akokshar
Last active March 25, 2018 12:21
Show Gist options
  • Save akokshar/423fadba9274dd5514b0e3cc4e66638c to your computer and use it in GitHub Desktop.
Save akokshar/423fadba9274dd5514b0e3cc4e66638c to your computer and use it in GitHub Desktop.
reflection
import kotlin.reflect.full.memberProperties
data class File(val type: Int = 0, val name: String)
private fun Any.serialize() = javaClass.kotlin.memberProperties.asSequence()
.filter {
when (it.get(this)) {
is String, is Int -> true
else -> false
}
}
.joinToString(separator = ", ", prefix = "{",postfix = "}") {
"${it.name}: ${it.get(this).toString()}"
}
fun main(args: Array<String>) {
val f = File(type = 1, name = "Filename")
println("json f : ${f.serialize()}");
val f1 = File(type = 0, name = "This is the name of the file")
println("json f1: ${f1.serialize()}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment