I have data class with the format-
data class ABC(
var first: String,
var second: String,
var third: String = "value"
)
I am using the below method to create an instance
T::class.java.getDeclaredConstructor().newInstance()
Now, this method calls the empty constructor and creates an instance with values of first as null, second as null and third as null , even though these are non-nullable field.
What I want is to create a instance with values of first as null, second as null but third as value.
Is there any way I can get the default value after creating the instance and than I will set the values manually?
I tried to directly get the memeber properties of the class but to call the property and get the value I have to pass the instance. If I pass the instance created with the above method I will get the value of third as null.
If you want an instance of
ABCwith propertiesnull,nulland default"value", you first need to declare the constructor to allow nullable properties:I would strongly recommend that you consider making the data class immutable, by using
valinstead ofvar, unless you really need it to be mutable.You're trying to use
T::class.java, which is not going to work because Java does not have a concept of default parameters. You need to useT::classinstead, which returns aKClass, part of Kotlin's reflection system which does understand default parameters.To use default parameters, create a map of required parameters to values, leaving out those that you want to leave as default: