Junior — Middle
Explain the concept of data class in Kotlin and how it differs from regular classes.
sobes.tech AI
Answer from AI
A data class in Kotlin is a special class designed for storing data. When declaring a class with the data keyword, the compiler automatically generates useful methods for it: equals(), hashCode(), toString(), as well as copy() functions and components for destructuring.
Differences from regular classes:
- Automatic generation of comparison and copying methods.
- Simplified syntax for creating classes that mainly contain data.
Example of a data class:
data class User(val name: String, val age: Int)
fun main() {
val user1 = User("Ivan", 30)
val user2 = user1.copy(age = 31)
println(user1) // User(name=Ivan, age=30)
println(user2) // User(name=Ivan, age=31)
}
Thus, a data class is convenient for data models where simplicity and correct object comparison are important.