0
0
Kotlinprogramming~20 mins

Why generics provide type safety in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generics Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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])
}
Aapple
Bbanana
Ccherry
DIndexOutOfBoundsException
Attempts:
2 left
💡 Hint
Look at the index used to access the list element.
🧠 Conceptual
intermediate
1:30remaining
Why generics prevent runtime errors
Why do generics in Kotlin help prevent runtime ClassCastException errors?
ABecause generics check types at compile time, preventing wrong types from being assigned.
BBecause generics convert all types to String automatically.
CBecause generics delay type checking until runtime.
DBecause generics allow any type without restrictions.
Attempts:
2 left
💡 Hint
Think about when type errors are caught in generic code.
🔧 Debug
advanced
2: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)
}
AThe println statement is incorrect syntax.
BThe list declaration is missing type parameters.
CThe cast from MutableList<Any> to MutableList<String> is unsafe and causes runtime errors.
DThe add method cannot add strings to a MutableList.
Attempts:
2 left
💡 Hint
Casting generic collections unsafely can break type safety.
📝 Syntax
advanced
2:00remaining
Correct generic function syntax
Which option correctly declares a generic function in Kotlin that returns the first element of a list?
Afun firstElement<T>(list: List<T>): T = list[0]
Bfun <T> firstElement(list: List<T>): T { return list.get(1) }
Cfun firstElement(list: List): T = list[0]
Dfun <T> firstElement(list: List<T>): T = list[0]
Attempts:
2 left
💡 Hint
Generic type parameters go before the function name.
🚀 Application
expert
3: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)
}
ANumber of animals: 2
BRuntime ClassCastException
CNumber of animals: 0
DType mismatch error at compile time
Attempts:
2 left
💡 Hint
Kotlin's List is covariant with 'out' keyword, allowing List to be passed as List.