copy
- Kotlin course
- Intermediate
- Lesson 14/116
- 5 min
Learn to copy data classes with copy.
The copy method
Data classes generate a copy method automatically. It produces a clone of the instance while changing some properties; the original is untouched.
Example: val q = p.copy(price = 20.0). Here q has the same properties as p but price becomes 20.0. p stays the same. Properties not mentioned as named arguments keep their original value. This is a common and safe way to modify data classes.
copy and named arguments
The copy method takes all parameters of the primary constructor as named arguments. You pass only the ones you want to change; the rest keep the original value.
Example: data class Product(val name: String, val price: Double). p.copy(name = "New") changes only name; price stays the same. p.copy() produces an exact clone. The order of named arguments does not matter; you can change any parameter.
Practice Define the Product data class and use copy
Define a data class named Product with a primary constructor taking val name: String, val price: Double. In main create a Product("Pen", 15.0) instance. Produce a q instance with p.copy(price = 20.0). Print p and q separately with println.
Starter code
// Define the Product data class
// with name and price properties
// instantiate, produce q via copy
// print p and qSample solution
data class Product(val name: String, val price: Double)
fun main() {
val p = Product("Pen", 15.0)
val q = p.copy(price = 20.0)
println(p)
println(q)
}Expected output
Product(name=Pen, price=15.0) Product(name=Pen, price=20.0)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the copy pattern
| Term | Meaning |
|---|---|
p.copy(price = 20.0) |
Clone with changed price |
p.copy() |
Exact clone |
val q = ... |
Assigning to a new instance |
p unchanged |
Original preserved |
2 What does <code>val q = p.copy(price = 20.0)</code> do?
- Sets p's price to 20.0
- Produces an exact clone of p
- Produces a new clone with price 20.0, p unchanged Correct answer
- Deletes p
Explanation: copy keeps the original and returns a modified clone.
3 Complete the copy call
val q = p.____(price = 20.0)
val q = p.copy(price = 20.0)
Explanation: The copy method produces a clone.