I was trying to convert a Map<String, Any>
to data class instance:
data class Person(
val name: String,
val age: Int,
val weight: Double?,
)
fun test() {
val map = mapOf(
"name" to "steven",
"age" to 30,
"weight" to 60,
)
val ctor = Person::class.constructors.first();
val params = ctor.parameters.associateWith {
map[it.name]
}
val instance = ctor.callBy(params)
println(instance)
}
The code above throws java.lang.IllegalArgumentException: argument type mismatch
because 60
is passed to weight
as an Int, and kotlin does not support implicit conversion.
Then I change the type of weight
to non-nullable Double
data class Person(
val name: String,
val age: Int,
val weight: Double, // !
)
and that works, even 60F
works too.
My question is:
Why implicit conversion works only when type is non-nullable?
How to do implicit conversion when type is nullable?