0
0
Kotlinprogramming~20 mins

Generic class declaration in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple generic class usage
What is the output of this Kotlin code that uses a generic class?
Kotlin
class Box<T>(val value: T) {
    fun getValue(): T = value
}

fun main() {
    val box = Box(123)
    println(box.getValue())
}
A123
BBox@<hashcode>
CCompilation error
Dnull
Attempts:
2 left
💡 Hint
Look at how the generic class stores and returns the value.
Predict Output
intermediate
2:00remaining
Output with generic class and type inference
What will this Kotlin program print when using a generic class with type inference?
Kotlin
class Container<T>(val item: T) {
    fun describe(): String = "Item is: $item"
}

fun main() {
    val c = Container("Hello")
    println(c.describe())
}
ACompilation error due to missing type
BItem is: Container@<hashcode>
CItem is: Hello
DItem is: null
Attempts:
2 left
💡 Hint
The generic type is inferred from the constructor argument.
🧠 Conceptual
advanced
2:00remaining
Understanding generic type constraints
Which option correctly declares a generic class in Kotlin that only accepts types which implement the Comparable interface?
Aclass Sortable<T>(val item: T) where T : Comparable<T>
Bclass Sortable<T>(val item: T) where T : Comparable
Cclass Sortable<T : Comparable>(val item: T)
Dclass Sortable<T : Comparable<T>>(val item: T)
Attempts:
2 left
💡 Hint
Look for the correct syntax for generic constraints in Kotlin.
Predict Output
advanced
2:00remaining
Output of generic class with nullable type
What is the output of this Kotlin code using a generic class with a nullable type parameter?
Kotlin
class Wrapper<T>(val value: T?) {
    fun isNull(): Boolean = value == null
}

fun main() {
    val w = Wrapper<String>(null)
    println(w.isNull())
}
Atrue
Bfalse
CCompilation error due to null value
DNullPointerException at runtime
Attempts:
2 left
💡 Hint
Check how the nullable type is handled in the class.
🔧 Debug
expert
3:00remaining
Identify the error in this generic class declaration
What error does this Kotlin code produce?
Kotlin
class Pair<T, U>(val first: T, val second: U) {
    fun swap(): Pair<U, T> {
        return Pair(second, first)
    }
}

fun main() {
    val p = Pair(1, "one")
    val swapped = p.swap()
    println("${swapped.first}, ${swapped.second}")
}
ACompilation error: unresolved reference to Pair in swap()
BOutput: one, 1
CRuntime error: StackOverflowError
DCompilation error: recursive call in constructor
Attempts:
2 left
💡 Hint
Constructor calls using the class name are valid inside class methods in Kotlin.