Sobes.tech
Junior

What is the purpose of a data class in Kotlin?

sobes.tech AI

Answer from AI

The Data class in Kotlin is designed for creating classes whose main purpose is to store data. The compiler automatically generates useful standard methods for them:

  • equals() and hashCode(): For comparing objects based on their properties.
  • toString(): Represents the object as a string displaying its properties and their values.
  • componentN(): For destructuring declarations (e.g., val (name, age) = user).
  • copy(): Creates a copy of the object, possibly with some properties' values changed.

Example:

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

fun main() {
    val user1 = User("Alice", 30)
    val user2 = User("Alice", 30)
    val user3 = user1.copy(age = 31)

    println(user1) // Will output something like "User(name=Alice, age=30)"
    println(user1 == user2) // Will output true, as they are compared by properties
    println(user1 === user2) // Will output false, as they are different objects
    println(user3) // Will output "User(name=Alice, age=31)"

    val (name, age) = user1
    println("$name is $age years old.") // Will output "Alice is 30 years old."
}