Junior — Middle
Is it mandatory to declare a constructor in data structures that use data class?
sobes.tech AI
Answer from AI
In Kotlin, where data classes are used, declaring a constructor is mandatory because the primary constructor is part of the data class syntax and defines the properties that will be automatically generated (e.g., equals(), hashCode(), toString(), copy()).
Example of a data class with a constructor:
data class User(val name: String, val age: Int)
If you do not declare a constructor, the compiler will throw an error because a data class requires at least one parameter in the primary constructor to generate methods.
Thus, the constructor in a data class is mandatory and serves to define the properties that will be used in the automatically generated methods.