Junior
What is the feature of Data Class compared to other classes in Kotlin?
sobes.tech AI
Answer from AI
Features of Data Class in Kotlin:
- Automatic generation of
equals(),hashCode(),toString(),copy(), andcomponentN()functions. - Require at least one parameter in the constructor.
- All constructor parameters must be declared as
valorvar. - Primarily designed for storing data.
Example:
// Regular class
class User(val name: String, val age: Int)
// Data Class
data class DataUser(val name: String, val age: Int)
fun main() {
val user1 = User("Alice", 30)
val user2 = User("Alice", 30)
println(user1 == user2) // false (compares references by default)
println(user1.toString()) // Will output something like User@hashcode
val dataUser1 = DataUser("Alice", 30)
val dataUser2 = DataUser("Alice", 30)
println(dataUser1 == dataUser2) // true (compares data)
println(dataUser1.toString()) // Will output DataUser(name=Alice, age=30)
}
Differences in generated functions:
| Function | Regular class | Data Class |
|---|---|---|
equals() |
Compares references | Compares data by fields |
hashCode() |
Depends on implementation | Depends on data by fields |
toString() |
Class name and hash code | Class name and field values |
copy() |
Not available (manual implementation needed) | Available (easily creates copies) |
componentN() |
Not available | Available (destructures object) |
Using componentN():
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(10, 20)
val (x, y) = p // Destructuring using component1(), component2()
println("x: $x, y: $y") // Will output x: 10, y: 20
}