Challenge - 5 Problems
Generics Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of generic list usage
What is the output of this Kotlin code that uses generics to ensure type safety?
Kotlin
fun main() { val list: List<String> = listOf("apple", "banana", "cherry") println(list[1]) }
Attempts:
2 left
💡 Hint
Look at the index used to access the list element.
✗ Incorrect
The list is a List containing three fruits. Accessing index 1 returns the second element, "banana".
🧠 Conceptual
intermediate1:30remaining
Why generics prevent runtime errors
Why do generics in Kotlin help prevent runtime ClassCastException errors?
Attempts:
2 left
💡 Hint
Think about when type errors are caught in generic code.
✗ Incorrect
Generics enforce type constraints during compilation, so wrong types cause errors before running the program.
🔧 Debug
advanced2:30remaining
Identify the type safety violation
Which option shows code that violates type safety despite using generics?
Kotlin
fun main() { val list: MutableList<Any> = mutableListOf("hello", 123) val strings: MutableList<String> = list as MutableList<String> strings.add("world") println(strings) }
Attempts:
2 left
💡 Hint
Casting generic collections unsafely can break type safety.
✗ Incorrect
Casting MutableList to MutableList bypasses compile-time checks and can cause ClassCastException at runtime.
📝 Syntax
advanced2:00remaining
Correct generic function syntax
Which option correctly declares a generic function in Kotlin that returns the first element of a list?
Attempts:
2 left
💡 Hint
Generic type parameters go before the function name.
✗ Incorrect
Option D correctly places before the function name and returns the first element at index 0.
🚀 Application
expert3:00remaining
Determine the output of generic variance
What is the output of this Kotlin code demonstrating generic variance with 'out' keyword?
Kotlin
open class Animal class Dog: Animal() fun printAnimals(animals: List<Animal>) { println("Number of animals: ${animals.size}") } fun main() { val dogs: List<Dog> = listOf(Dog(), Dog()) printAnimals(dogs) }
Attempts:
2 left
💡 Hint
Kotlin's List is covariant with 'out' keyword, allowing List to be passed as List.
✗ Incorrect
Because List is declared as List, List can be used where List is expected, so the function prints the size 2.