Junior — Middle
Is it possible to automatically generate a parameterless constructor for a data class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a data class automatically generates a constructor that takes all properties declared in the primary constructor. However, if you want a parameterless constructor (default constructor), it is not generated automatically if the primary constructor has parameters without default values.
To get a parameterless constructor, you can:
- Provide default values for all primary constructor parameters:
data class User(val name: String = "", val age: Int = 0)
Now, you can create a User() object without parameters.
- Or, add an additional parameterless constructor manually:
data class User(val name: String, val age: Int) {
constructor() : this("", 0)
}
Thus, automatic generation of a parameterless constructor for data class is only possible when all parameters have default values.