Sobes.tech
Junior

What methods are available in data class in Kotlin?

sobes.tech AI

Answer from AI

A data class in Kotlin automatically generates the following methods:

  • equals(): Compares objects based on the values of properties declared in the constructor.
  • hashCode(): Generates a hash code based on the properties declared in the constructor.
  • toString(): Returns a string representation of the object in the format "ClassName(prop1=value1, prop2=value2)".
  • copy(): Creates a new object by copying the properties of the original, with the possibility to modify some properties.
  • componentN(): Generates functions component1(), component2(), etc., for each property in the order they are declared, allowing destructuring declarations.
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

    // hashCode()
    println(user1.hashCode())
    println(user2.hashCode())

    // 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 Declaration
    val (name, age) = user1
    println("Name: $name, Age: $age") // Name: Alice, Age: 30
}
What methods are available in data class in Kotlin… - sobes.tech