I have data class with default values.
data class Project(
val code: String,
val name: String,
val categories: List<String> = emptyList())
Java reflection fails to instantiate the class when some values are null. I'm getting exception
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method Project.<init>, parameter categories
This is because java.lang.reflect.Constructor<T>.instantiateClass
method expects arguments that are not null.
I have the type information, I have the constructor definition but I'm not sure how to call the constructor so that it uses the default values (The values are coming from the database and categories
can be null
). Is there any way to achieve this in Kotlin?
The Kotlin default parameters are not compatible with Java reflection, meaning there's no simple way to use them together, because the Kotlin default parameters actually work with a separate method under the hood that is also passed a bit mask to specify which arguments are default.
There are two ways to fix this.
Use Kotlin reflection. For example, the
callBy
function supports default parameters, they can be omitted from the map.Use
@JvmOverloads
to generate an overload without the default parameterwhich can be called in Java.