0
0
Kotlinprogramming~20 mins

Data classes for value holders in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Data Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
APoint(x=3, y=10)
BPoint(x=3, y=5)
CPoint(x=10, y=5)
DCompilation error
Attempts:
2 left
💡 Hint
The copy function creates a new instance with specified changes.
Predict Output
intermediate
2: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)
}
Atrue
BRuntime exception
CCompilation error
Dfalse
Attempts:
2 left
💡 Hint
Data classes automatically implement equals based on properties.
🔧 Debug
advanced
2: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
}
AMissing primary constructor
BData classes cannot have var properties
CData classes cannot have properties with initializers
DProperty 'name' is declared twice causing a conflict
Attempts:
2 left
💡 Hint
Check how properties are declared in the primary constructor and class body.
🧠 Conceptual
advanced
1: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)
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Each property declared in the primary constructor generates a component function.
Predict Output
expert
2: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")
}
ABook(title=1984, author=Orwell, year=1949)
BCompilation error due to destructuring
C1984 by Orwell, published in 1949
DRuntime exception
Attempts:
2 left
💡 Hint
Data classes support destructuring declarations matching their properties.