From Java to Kotlin – Part IV: Copying objects
Considering a move to Kotlin? Coming from a Java background? In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin. While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.
Case 4: Copying objects should be easy.
And safe. And boring.
The problem
We want to create a modified copy of an object. Immutability preferred. No side effects.
The Java way
public record JavaPerson(String name, Integer age) {
public JavaPerson() {
this("John Doe", 100);
}
public JavaPerson copy(String name, Integer age) {
return new JavaPerson(name != null ? name : this.name, age != null ? age : this.age);
}
}
Usage:
var p2 = JavaPerson.copy("Piet", null);
This works, but:
-
Requires a custom method
-
Needs null checks
-
Is easy to get wrong
The Kotlin way
Data classes give you copy() for free.
data class KotlinPerson(val name: String = "John Doe", val age: Int = 100) { }
Usage:
val p2 = kotlinperson.copy(name = "Piet")
No nulls. No overloads. No guessing.
Why this matters
Immutability becomes practical when copying is cheap and readable. Kotlin makes the right thing easy.
Takeaway
Java is powerful.
Kotlin’s copy() is peaceful.
Choose peace.