Sobes.tech
Junior

How to implement and use data classes in Kotlin?

sobes.tech AI

Answer from AI

Data classes are used for storing data. The compiler automatically generates useful methods for them, such as equals(), hashCode(), toString(), copy(), and componentN() functions.

Implementation: declare a class with the data prefix.

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

Usage:

Creating an instance:

val user = User("Alice", 30)

Accessing properties:

val name = user.name // Alice
val age = user.age   // 30

Using generated methods:

println(user.toString()) // User(name=Alice, age=30)

val anotherUser = User("Alice", 30)
println(user == anotherUser) // true (equals() is generated)

val olderUser = user.copy(age = 31) // User(name=Alice, age=31)

val (userName, userAge) = user // Destructuring
println("Name: $userName, Age: $userAge") // Name: Alice, Age: 30

Features:

  • All primary constructor parameters must be either val or var.
  • Data classes cannot be abstract, open, sealed, or inner.
  • Properties from the class body are not involved in the generation of methods (equals, hashCode, copy, componentN).
data class Person(val name: String) {
    var height: Int = 0 // Not involved in equals/hashCode/copy/componentN
}

val p1 = Person("Bob")
p1.height = 180
val p2 = Person("Bob")
p2.height = 190
println(p1 == p2) // true
How to implement and use data classes in Kotlin… - sobes.tech