By default, the data classes in Kotlin automatically generate the primary construction which takes the parameter of the declared members. This constructor will initialize all the properties at the time of object creation. The primary constructor does not provide an empty constructor.
So, to create an empty constructor for a data class in Kotlin, we need to explicitly define the secondary constructor with no parameters. This allows us to create instances of the data class without providing the initial values.
Following is an example of how to create an empty constructor for data class.
data class Person(val name: String, val age: Int) {
constructor() : this("", 0)
}
fun main() {
val person = Person()
println("Name: ${person.name}, Age: ${person.age}")
}
In the above example, we have a data class Person
with the members as name & age. By defining a secondary constructor with no parameters, we can initialize the above members with some default values.
In the main function, we created the instance with the empty constructor and the default value is assigned to it.
Following is the real-time example where we use the empty constructor for the data class
Consider the following user registration form where we have various fields such as name, email, username, and password. By using an empty constructor in the user data class, we can create an instance to hold the form data without initializing the properties.
The empty constructor allows us to create a user object without providing initial values, and then assign the properties dynamically based on user input.
data class User(
val name: String = "",
val email: String = "",
val username: String = "",
val password: String = ""
)
fun main() {
val user = User()
// Populate the user object with form data
user.name = "Arjun kumar"
user.email = "arjun@example.com"
user.username = "arjun"
user.password = "password123"
// Perform user registration logic
}