Given a simple data class like:
data class TestSimple(
val country: String,
var city: String? = null,
var number: Int? = null,
var code: Long? = null,
var amount: Float? = null,
var balance: Double? = null
)
Is there any way I can use kotlin-reflect
to find the data type of the properties? I got all the properties via:
val allFields = this::class.declaredMemberProperties.map {
it.name to it
}.toMap()
I only got as far as allFields["number"].returnType
which returns a KType
. I couldn't figure out a way to check if a KType
is Int
or Long
.
I am trying to avoid the code I currently use to cast the incoming JSON numeric data to appropriate data type:
fun castToLong(value: Any): Long {
val number = try {
value as Number
} catch (e: Exception) {
throw Exception("Failed to cast $value to a Number")
}
return number.toLong()
}