Junior — Middle
Can you name the main constructors used in Data Class?
sobes.tech AI
Answer from AI
In Kotlin, a Data Class automatically generates several constructors and functions, but the main constructors that are typically used are:
- Primary constructor: declared in the class header and takes parameters for all the properties of the class.
Example:
data class User(val name: String, val age: Int)
Here, the primary constructor takes name and age.
- Copy constructor (copy): allows creating a copy of an object with the possibility to change some fields.
Example:
val user1 = User("Alice", 30)
val user2 = user1.copy(age = 31)
- Parameters with default values: allow creating objects with partially specified parameters.
Example:
data class User(val name: String = "Unknown", val age: Int = 0)
val user = User()
Thus, the primary constructor with parameters and the copy functionality are key constructors in a Data Class.