Challenge - 5 Problems
Generic Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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()) }
Attempts:
2 left
💡 Hint
Look at how the generic class stores and returns the value.
✗ Incorrect
The generic class Box stores the value 123 of type Int. The getValue() method returns this value, so the output is 123.
❓ Predict Output
intermediate2: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()) }
Attempts:
2 left
💡 Hint
The generic type is inferred from the constructor argument.
✗ Incorrect
The Container class holds a String "Hello". The describe() method returns the string with the item included, so it prints "Item is: Hello".
🧠 Conceptual
advanced2:00remaining
Understanding generic type constraints
Which option correctly declares a generic class in Kotlin that only accepts types which implement the Comparable interface?
Attempts:
2 left
💡 Hint
Look for the correct syntax for generic constraints in Kotlin.
✗ Incorrect
Option D correctly uses the syntax T : Comparable to constrain T to types that implement Comparable of themselves. Option D is valid Kotlin syntax but less idiomatic here; the 'where' clause is typically used for multiple constraints. Options B and C have syntax errors.
❓ Predict Output
advanced2: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()) }
Attempts:
2 left
💡 Hint
Check how the nullable type is handled in the class.
✗ Incorrect
The Wrapper class accepts a nullable type T?. The value is null, so isNull() returns true and prints true.
🔧 Debug
expert3: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}") }
Attempts:
2 left
💡 Hint
Constructor calls using the class name are valid inside class methods in Kotlin.
✗ Incorrect
The code compiles successfully. The swap() method creates a new Pair instance using Pair(second, first), where the types are inferred correctly from the return type and arguments. The program prints "one, 1".