Junior — Middle
What are the main advantages and disadvantages of using data class in your project?
sobes.tech AI
Answer from AI
Data class in Android (Kotlin) provides a convenient way to create classes for storing data with automatic generation of equals(), hashCode(), toString(), and copy() methods.
Advantages:
- Less boilerplate code, which simplifies maintenance.
- Convenience of copying objects with modifications to some fields via copy().
- Clear representation of data structure.
Disadvantages:
- Not suitable for classes with logic, as data classes are intended specifically for data storage.
- Changing the structure of a data class may require data migration.
Example:
data class User(val id: Int, val name: String)
val user1 = User(1, "Alice")
val user2 = user1.copy(name = "Bob")
println(user2) // User(id=1, name=Bob)