Bird
Raised Fist0
Kotlinprogramming~10 mins

Data class copy and destructuring in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Data class copy and destructuring
Create data class instance
↓
Destructure instance into variables
↓
Use copy() to create modified instance
↓
Compare original and copied instances
↓
End
This flow shows creating a data class object, breaking it into variables, copying it with changes, and comparing both objects.
Execution Sample
Kotlin
data class User(val name: String, val age: Int)

fun main() {
  val user1 = User("Alice", 30)
  val (name, age) = user1
  val user2 = user1.copy(age = 31)
  println("$name is $age years old")
  println(user2)
}
Creates a User, destructures it, copies with a changed age, then prints values.
Execution Table
StepActionEvaluationResult
1Create user1User("Alice", 30)user1 = User(name=Alice, age=30)
2Destructure user1(name, age) = user1name = "Alice", age = 30
3Copy user1 with age=31user1.copy(age=31)user2 = User(name=Alice, age=31)
4Print name and ageprintln("$name is $age years old")Output: Alice is 30 years old
5Print user2println(user2)Output: User(name=Alice, age=31)
6EndNo more codeProgram ends
💡 Program ends after printing both original and copied user details.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
user1undefinedUser(name=Alice, age=30)User(name=Alice, age=30)User(name=Alice, age=30)User(name=Alice, age=30)
nameundefinedundefined"Alice""Alice""Alice"
ageundefinedundefined303030
user2undefinedundefinedundefinedUser(name=Alice, age=31)User(name=Alice, age=31)
Key Moments - 2 Insights
Why does the destructured 'age' variable stay 30 even after copying user1 with age 31?
Because destructuring happens before the copy. The variable 'age' holds the original value from user1 (30), not from the copied user2.
Does the copy() function change the original user1 object?
No, copy() creates a new object with the specified changes. user1 remains unchanged as shown in step 3 and variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3. What is the value of user2?
AUser(name=Alice, age=30)
BUser(name=Alice, age=31)
CUser(name=Bob, age=31)
DUser(name=Bob, age=30)
💡 Hint
Check the 'Result' column at step 3 in the execution_table.
At which step does the variable 'name' get assigned the value "Alice"?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns for when destructuring happens.
If we changed user1.copy(age = 35) instead of 31, what would user2's age be in the variable_tracker after step 3?
A35
B31
C30
DUndefined
💡 Hint
The copy() function sets the new age value in user2 as shown in step 3.
Concept Snapshot
Data class copy and destructuring in Kotlin:
- Use 'val (a, b) = obj' to unpack properties.
- Use 'obj.copy(prop = newVal)' to create modified copies.
- Original object stays unchanged.
- Destructured variables keep original values.
- Useful for easy object cloning and unpacking.
Full Transcript
This example shows how Kotlin data classes let you easily copy objects and break them into variables. First, we create a User named Alice aged 30. Then we unpack her name and age into separate variables. Next, we make a copy of Alice but change her age to 31. When printing, the destructured age is still 30 because it was taken before copying. The copy creates a new User with the updated age, leaving the original unchanged. This helps manage data cleanly and simply.

Practice

(1/5)
1.

What does the copy() function do in a Kotlin data class?

easy
A. Changes the original object directly.
B. Deletes the original object and creates a new one.
C. Creates a new object with the same properties, optionally changing some.
D. Converts the object to a string representation.

Solution

  1. Step 1: Understand the purpose of copy()

    The copy() function in Kotlin data classes creates a new instance with the same property values.
  2. Step 2: Recognize optional property changes

    You can specify new values for some properties while copying, leaving others unchanged.
  3. Final Answer:

    Creates a new object with the same properties, optionally changing some. -> Option C
  4. Quick Check:

    copy() = new object with changes [OK]
Hint: Remember: copy() clones with optional changes [OK]
Common Mistakes:
  • Thinking copy() modifies the original object
  • Confusing copy() with toString()
  • Assuming copy() deletes the original
2.

Which of the following is the correct syntax to copy a Kotlin data class Person and change only the age property?

data class Person(val name: String, val age: Int)
easy
A. val newPerson = person.copy(age = 30)
B. val newPerson = person.copy(30)
C. val newPerson = copy(person, age = 30)
D. val newPerson = person.copy(name = "John")

Solution

  1. Step 1: Recall the copy() syntax

    The copy() function uses named arguments to change specific properties.
  2. Step 2: Identify correct usage

    Using person.copy(age = 30) changes only the age, keeping name same.
  3. Final Answer:

    val newPerson = person.copy(age = 30) -> Option A
  4. Quick Check:

    copy() uses named args for changes [OK]
Hint: Use named arguments inside copy() to change properties [OK]
Common Mistakes:
  • Passing values without property names
  • Using copy() as a standalone function
  • Changing wrong property by mistake
3.

What is the output of this Kotlin code?

data class Point(val x: Int, val y: Int)

fun main() {
    val p1 = Point(5, 10)
    val (a, b) = p1
    val p2 = p1.copy(y = 20)
    println("a = $a, b = $b")
    println(p2)
}
medium
A. a = 5, b = 20 Point(x=5, y=10)
B. a = 5, b = 10 Point(x=5, y=20)
C. a = 10, b = 5 Point(x=5, y=20)
D. a = 5, b = 10 Point(x=5, y=10)

Solution

  1. Step 1: Understand destructuring of p1

    Destructuring assigns a = p1.x = 5 and b = p1.y = 10.
  2. Step 2: Understand copy() usage

    p2 is a copy of p1 with y changed to 20, so Point(x=5, y=20).
  3. Final Answer:

    a = 5, b = 10 Point(x=5, y=20) -> Option B
  4. Quick Check:

    Destructuring + copy() = expected values [OK]
Hint: Destructure original, copy with changed property [OK]
Common Mistakes:
  • Mixing up destructured values
  • Assuming copy changes original
  • Printing wrong variable
4.

Find the error in this Kotlin code snippet:

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

fun main() {
    val user1 = User("Alice", 25)
    val (n, a) = user1.copy(age = 30)
    println("Name: $n, Age: $a")
}
medium
A. Variable names in destructuring must match property names.
B. Destructuring cannot be done on copy() result.
C. copy() requires all properties to be specified.
D. No error; code runs and prints updated age.

Solution

  1. Step 1: Check copy() usage

    The copy() function is correctly called with age = 30.
  2. Step 2: Check destructuring

    Destructuring works on the copy result, assigning n = "Alice" and a = 30.
  3. Final Answer:

    No error; code runs and prints updated age. -> Option D
  4. Quick Check:

    copy() + destructuring works fine [OK]
Hint: copy() returns data class instance usable for destructuring [OK]
Common Mistakes:
  • Thinking destructuring fails on copy() result
  • Believing copy() needs all properties
  • Confusing variable names with property names
5.

Given this data class and list, how do you create a new list of Person objects with age increased by 1, using copy() and destructuring?

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

val people = listOf(Person("Tom", 20), Person("Sue", 25))
hard
A. people.map { it.copy(age = it.age + 1) }
B. people.forEach { it.copy(age = it.age + 1) }
C. people.copy { age += 1 }
D. people.map { (n, a) -> Person(n, a + 1) }

Solution

  1. Step 1: Understand list transformation

    We want to create a new list with each person's age increased by 1.
  2. Step 2: Use copy() inside map()

    Using map with it.copy(age = it.age + 1) creates new objects with updated age.
  3. Final Answer:

    people.map { it.copy(age = it.age + 1) } -> Option A
  4. Quick Check:

    map + copy() = new list with changed ages [OK]
Hint: Use map with copy() to update properties in list [OK]
Common Mistakes:
  • Using forEach which returns Unit, not a list
  • Trying to copy the whole list directly
  • Ignoring destructuring or copy() usage
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard