Sobes.tech
Junior — Middle

What are the distinctive features of data classes compared to regular classes in programming languages?

sobes.tech AI

Answer from AI

A data class in programming languages (for example, Kotlin) is a special class designed for storing data. Unlike regular classes, a data class automatically generates a number of useful methods:

  • equals() and hashCode() — for comparing objects by content.
  • toString() — for convenient output of the object's content.
  • copy() — for creating a copy of the object with the ability to modify some fields.
  • componentN() functions — for destructuring the object.

Example in Kotlin:

data class User(val name: String, val age: Int)

val user1 = User("Ivan", 30)
println(user1) // User(name=Ivan, age=30)

val user2 = user1.copy(age = 31)
println(user2) // User(name=Ivan, age=31)

Thus, a data class simplifies working with objects that serve as containers for data, eliminating the need to manually write often repetitive code.

What are the distinctive features of data classes… - sobes.tech