Junior — Middle
Milline on vahe andmeklassi ja tavalise klassi vahel programmeerimiskeeles?
sobes.tech AI
Vastus AI-lt
In Kotlin (Android), a data class is a special class designed for storing data. The main difference from a regular class is that the compiler automatically generates several useful methods:
equals()andhashCode()for comparing objects by content,toString()with informative output,copy()for creating copies with modified fields,- components (
component1(),component2(), etc.) for destructuring.
A regular class does not have these methods by default; they need to be written manually if needed.
Example of a data class:
data class User(val name: String, val age: Int)
val user1 = User("Alice", 30)
val user2 = user1.copy(age = 31)
println(user1) // User(name=Alice, age=30)
Thus, data classes are convenient for data models where simplicity and correct comparison of objects are important.