Skip to Content
Course content

203: Common Kotlin Interview Questions on Data Classes

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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:

  1. Modify the Player data class to ensure it can be safely used as a key in a HashSet without becoming "lost" when their stats change.
  2. Update the updateScore function to follow the immutable pattern (using copy()) instead of mutating the object directly.
  3. 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)
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.