-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
203: Common Kotlin Interview Questions on Data Classes
I can't tell you how many candidates I've watched freeze up during a technical interview when I ask them exactly what happens under the hood of a Kotlin data class. The most common mistake isn't a lack of knowledge about the syntax—it's a fundamental misunderstanding of how copy() works. Many developers believe that calling copy() creates a "deep clone" of the object, meaning every object inside the class is also duplicated.
Let's prove why that's wrong immediately. Look at this snippet:
data class Project(val name: String, val tags: MutableList<String>)
fun main() {
val original = Project("KotlinCourse", mutableListOf("Education", "Programming"))
val cloned = original.copy()
cloned.tags.add("InterviewPrep")
println("Original tags: ${original.tags}")
// Output: Original tags: [Education, Programming, InterviewPrep]
}
Wait, what? I modified the cloned object, but the original object changed too. This happens because copy() performs a shallow copy. It copies the reference to the list, not the list itself. If you're in an interview and you claim copy() creates a fully independent instance of a complex object, you've just walked into a trap.
copy() is Shallow, Not Deep
In Kotlin, the copy() method generated for data classes only duplicates the values of the properties. For primitive types (like Int or Boolean) and immutable types (like String), this feels like a deep copy because those values can't be changed. But for any mutable object—a MutableList, a HashMap, or even another custom class with var properties—both the original and the copy will point to the exact same object in memory.
If you actually need a deep copy, you'll have to implement it yourself, perhaps by creating a new list in the constructor or using a serialization library. I usually recommend avoiding mutable collections in data classes entirely to prevent this headache.
The Myth that 'data' Equals Immutable
Another point that comes up constantly is the assumption that making a class a data class automatically makes it immutable. It doesn't. The data keyword simply tells the compiler to generate equals(), hashCode(), toString(), and copy(). It has nothing to do with whether your properties can be changed.
// This is a data class, but it's totally mutable
data class UserProfile(var username: String, var bio: String)
val profile = UserProfile("kotlin_dev", "I love JVM")
profile.username = "kotlin_pro" // Perfectly legal, but potentially dangerous
If you want immutability, you must use val. In my experience, the most robust architecture uses data class combined with val properties. This forces you to use copy() to create new versions of your state, which makes your code much easier to debug in multi-threaded environments.
The HashCode Trap with Mutable State
This is the "senior level" interview question. I'll ask: "What happens if you use a data class with a var property as a key in a HashMap?"
Here is the disaster scenario: hashCode() is generated based on the properties defined in the primary constructor. If you change a var property after the object has been placed in a HashSet or HashMap, the object's hash code changes. However, the map has already stored the object in a "bucket" based on the old hash code.
data class Player(var id: Int, var name: String)
val players = hashSetOf(Player(1, "Alice"))
val alice = players.first()
alice.name = "Bob" // This changes the hashCode!
println(players.contains(alice)) // Output: false
The object is still physically inside the set, but the set can't find it anymore because it's looking in the wrong bucket. It's essentially a memory leak that's incredibly hard to track down. My rule of thumb: never use a data class as a Map key unless all its primary constructor properties are val.
📋 Practical Task
Fixing the PlayerRegistry Memory Leak
You have been handed a piece of legacy code for a game server. The PlayerRegistry uses a HashSet to track active players. However, players are reporting that they are "disappearing" from the registry even though they are still connected. This is happening because the Player data class uses var for properties that change frequently.
Your Task:
- Modify the
Playerdata class to ensure it can be safely used as a key in aHashSetwithout becoming "lost" when their stats change. - Update the
updateScorefunction to follow the immutable pattern (usingcopy()) instead of mutating the object directly. - Ensure that the registry is updated with the new instance of the player.
data class Player(val id: Int, var score: Int, var level: Int)
class PlayerRegistry {
private val activePlayers = hashSetOf<Player>()
fun addPlayer(player: Player) {
activePlayers.add(player)
}
fun updateScore(player: Player, newScore: Int) {
// BUG: This mutates the object inside the HashSet
player.score = newScore
}
fun isPlayerActive(player: Player): Boolean {
return activePlayers.contains(player)
}
}
There are no comments for now.