0
0
Kotlinprogramming~5 mins

Data class copy and destructuring in Kotlin

Choose your learning style9 modes available
Introduction

Data classes help you store data easily. Copying lets you make a new object with some changes. Destructuring helps you get parts of the data quickly.

When you want to create a similar object but change a few values.
When you want to get multiple values from an object in simple variables.
When you want to avoid writing many lines to copy or access data.
When you want to keep your code clean and easy to read.
Syntax
Kotlin
data class Person(val name: String, val age: Int)

val person1 = Person("Anna", 25)

// Copying
val person2 = person1.copy(age = 30)

// Destructuring
val (name, age) = person1

The copy() function creates a new object with the same values, but you can change some.

Destructuring lets you assign properties to variables in one line.

Examples
Copy person1 but change age to 26.
Kotlin
data class Person(val name: String, val age: Int)

val person1 = Person("Anna", 25)
val person2 = person1.copy(age = 26)
Get name and age from person1 into variables.
Kotlin
val (name, age) = person1
println(name)
println(age)
Copy person1 but change name to John.
Kotlin
val person3 = person1.copy(name = "John")
println(person3)
Sample Program

This program shows how to copy a data class object with a changed age and how to get its properties using destructuring.

Kotlin
data class Person(val name: String, val age: Int)

fun main() {
    val person1 = Person("Anna", 25)
    val person2 = person1.copy(age = 30)

    val (name, age) = person2

    println("Original: $person1")
    println("Copied: $person2")
    println("Destructured name: $name")
    println("Destructured age: $age")
}
OutputSuccess
Important Notes

Copying does not change the original object.

Destructuring works because data classes automatically create component functions.

Summary

Data classes store data simply.

copy() makes a new object with some changes.

Destructuring extracts values into variables easily.