Challenge - 5 Problems
Data Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of data class copy with modification
What is the output of this Kotlin code using a data class and the copy function?
Kotlin
data class Point(val x: Int, val y: Int) fun main() { val p1 = Point(3, 5) val p2 = p1.copy(y = 10) println(p2) }
Attempts:
2 left
💡 Hint
The copy function creates a new instance with specified changes.
✗ Incorrect
The copy function creates a new Point with the same x value and the new y value 10.
❓ Predict Output
intermediate2:00remaining
Equality check between data class instances
What will be the output of this Kotlin program?
Kotlin
data class User(val name: String, val age: Int) fun main() { val user1 = User("Alice", 30) val user2 = User("Alice", 30) println(user1 == user2) }
Attempts:
2 left
💡 Hint
Data classes automatically implement equals based on properties.
✗ Incorrect
Data classes compare all properties for equality, so user1 == user2 is true.
🔧 Debug
advanced2:00remaining
Why does this data class fail to compile?
This Kotlin data class code fails to compile. What is the cause?
Kotlin
data class Person(var name: String, val age: Int) { var name: String = name }
Attempts:
2 left
💡 Hint
Check how properties are declared in the primary constructor and class body.
✗ Incorrect
The property 'name' is declared in the constructor and again inside the class body, causing a duplicate declaration error.
🧠 Conceptual
advanced1:30remaining
Number of components in a data class
Given this Kotlin data class, how many component functions are generated automatically?
Kotlin
data class Rectangle(val width: Int, val height: Int, val color: String)
Attempts:
2 left
💡 Hint
Each property declared in the primary constructor generates a component function.
✗ Incorrect
Each property (width, height, color) generates a component function: component1(), component2(), component3().
❓ Predict Output
expert2:30remaining
Output of destructuring declaration with data class
What is the output of this Kotlin program?
Kotlin
data class Book(val title: String, val author: String, val year: Int) fun main() { val book = Book("1984", "Orwell", 1949) val (t, a, y) = book println("$t by $a, published in $y") }
Attempts:
2 left
💡 Hint
Data classes support destructuring declarations matching their properties.
✗ Incorrect
The destructuring declaration assigns each property to variables t, a, y, which are printed in the string.