Junior — Middle
Is it possible to declare fields in a data class only inside the class body without modifying the constructor?
sobes.tech AI
Answer from AI
In Kotlin, for data classes, properties are usually declared in the primary constructor so that they automatically participate in the equals(), hashCode(), toString(), and copy() methods.
However, properties can be declared inside the class body, but then they will not be considered in the automatically generated data class methods. This can lead to unexpected behavior.
Example:
data class User(val name: String) {
var age: Int = 0 // declared inside the class body
}
In this example, age will not be part of the equals(), hashCode(), and other methods generated for the data class.
Therefore, if a field should participate in these methods, it needs to be declared in the constructor. If the field is used for internal state and should not affect comparison, it can be declared inside the class body.