Junior — Middle
Can you explain the differences between a regular class and a data class in programming language?
sobes.tech AI
Answer from AI
In programming languages like Kotlin, a regular class and a data class differ in that a data class is intended for storing data and automatically generates useful methods.
Main differences between a data class and a regular class:
- Automatic method generation:
equals(),hashCode(),toString(),copy(), as well as component functions for destructuring. - Constructor with parameters: a data class must have at least one parameter in the primary constructor.
- Usage: data class is convenient for data models where equality semantics based on content are important.
Example in Kotlin:
data class User(val name: String, val age: Int)
val user1 = User("Alice", 30)
val user2 = User("Alice", 30)
println(user1 == user2) // true, content comparison
println(user1) // User(name=Alice, age=30)
val user3 = user1.copy(age = 31) // creates a new object with a changed age
In a regular class, these methods need to be implemented manually, which increases code and the likelihood of errors.