Sobes.tech
Junior

How do data classes work in Kotlin?

sobes.tech AI

Answer from AI

Data classes in Kotlin are used for storing data. The compiler automatically generates standard methods for them:

  • equals(): Compares instances based on the values of their properties.
  • hashCode(): Generates a hash code based on the property values.
  • toString(): Returns a string representation including the names and values of all properties.
  • copy(): Creates a copy of the object, optionally changing the values of specified properties.
  • componentN(): Methods for destructuring (breaking down the object into individual properties).
// Example data class
data class User(val name: String, val age: Int)

fun main() {
    val user1 = User("Alice", 30)
    val user2 = User("Alice", 30)
    val user3 = User("Bob", 25)

    // equals()
    println(user1 == user2) // true
    println(user1 == user3) // false

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

    // copy()
    val user4 = user1.copy(age = 31)
    println(user4) // User(name=Alice, age=31)

    // componentN() and destructuring
    val (name, age) = user1
    println("Name: $name, Age: $age") // Name: Alice, Age: 30
}

Key points:

  • All properties declared in the primary constructor must be either val or var.
  • Data classes cannot be abstract, open, sealed, or inner.
  • Data classes can inherit from other classes or implement interfaces.
  • Properties declared outside the primary constructor are not included in the generated methods.
Method Description
equals() Compares properties from the primary constructor.
hashCode() Generates a hash based on properties from the primary constructor.
toString() Outputs a string representation of properties from the primary constructor.
copy() Creates a shallow copy with the ability to modify properties.
componentN() Provides access to properties in the order they are declared in the constructor.

Data classes greatly simplify working with POJO (Plain Old Java Object) or DTO (Data Transfer Object), reducing boilerplate code.

How do data classes work in Kotlin? — Kotlin - sobes.tech