Junior — Middle
What operations and capabilities does using a data class provide in a programming language?
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 several useful methods:
equals()andhashCode()— for comparing objects by value, not by reference.toString()— for convenient output of the object's contents.copy()— for creating a copy of the object with the ability to modify some properties.componentN()functions — for destructuring the object.
Example:
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)
val (name, age) = user1
println("Name: $name, Age: $age")
}
Thus, data class simplifies working with objects that primarily contain data, reducing boilerplate code.