Junior
What variables can be used in a data class?
sobes.tech AI
Answer from AI
In a data class, the following can be used:
val(read-only property): The property is initialized when the object is created and cannot be changed afterwards. It is part of the automatically generated methods (equals(),hashCode(),toString(),copy()).var(mutable property): The property can be changed after the object is created. It is also part of the generated methods.- Properties declared in the class body: These properties are not part of the main properties of the data class and do not participate in the generation of standard methods.
Example:
data class User(
val id: Int, // read-only, part of main properties
var name: String, // mutable, part of main properties
val creationTime: Long = System.currentTimeMillis() // read-only, with default value, part of main properties
) {
val isAdmin: Boolean = false // read-only, not part of main properties, not included in equals/hashCode/toString
}