Bird
Raised Fist0
Kotlinprogramming~20 mins

Why generics provide type safety in Kotlin - Challenge Your Understanding

Choose your learning style10 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.

Practice

(1/5)
1. Why do generics in Kotlin help provide type safety?
easy
A. They automatically convert types at runtime.
B. They allow any type without restrictions.
C. They make the program run faster.
D. They check types at compile time to prevent errors.

Solution

  1. Step 1: Understand generics role in type checking

    Generics allow specifying the type a class or function works with, so the compiler can check if the correct type is used.
  2. Step 2: Identify how this prevents errors

    By checking types early, generics prevent mixing incompatible types, avoiding bugs before running the program.
  3. Final Answer:

    They check types at compile time to prevent errors. -> Option D
  4. Quick Check:

    Generics = Compile-time type checks [OK]
Hint: Generics catch wrong types before running code [OK]
Common Mistakes:
  • Thinking generics allow any type without checks
  • Believing generics speed up runtime
  • Confusing compile-time and runtime type checks
2. Which of the following is the correct syntax to declare a generic class in Kotlin?
easy
A. class Box { var value: T }
B. class Box<T> { var value: T }
C. class Box<T> { var value: Int }
D. class Box<T> (value: T) : T

Solution

  1. Step 1: Review generic class syntax

    In Kotlin, generic classes declare a type parameter inside angle brackets after the class name, like class Box<T>.
  2. Step 2: Check property type usage

    The property inside should use the generic type T, not a fixed type like Int.
  3. Final Answer:

    class Box<T> { var value: T } -> Option B
  4. Quick Check:

    Generic class syntax = class Box<T> { var value: T } [OK]
Hint: Generic type goes in angle brackets after class name [OK]
Common Mistakes:
  • Using fixed types instead of generic type parameter
  • Omitting the generic type parameter declaration
  • Incorrect inheritance syntax with generics
3. What will be the output of this Kotlin code?
fun main() {
    val list: List<String> = listOf("apple", "banana")
    val first: String = list[0]
    println(first.length)
}
medium
A. Syntax error
B. Runtime error
C. 5
D. 0

Solution

  1. Step 1: Understand the list type and access

    The list is declared as List<String>, so it only holds strings. Accessing list[0] returns "apple".
  2. Step 2: Calculate the length of the first string

    "apple" has 5 characters, so first.length is 5, which is printed.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    "apple" length = 5 [OK]
Hint: Check type and value before output [OK]
Common Mistakes:
  • Confusing list element type causing errors
  • Expecting runtime error due to generics
  • Miscounting string length
4. Identify the error in this Kotlin code using generics:
fun printFirst(list: List<Int>) {
    val first = list[0]
    println(first.length)
}
medium
A. Cannot call length on Int type
B. List<Int> cannot be indexed
C. Missing generic type declaration
D. Function return type is missing

Solution

  1. Step 1: Analyze the list element type

    The list holds Int values, so first is an integer.
  2. Step 2: Check the method called on the element

    Calling length on an integer is invalid because Int does not have a length property.
  3. Final Answer:

    Cannot call length on Int type -> Option A
  4. Quick Check:

    Int has no length property [OK]
Hint: Check methods valid for the generic type used [OK]
Common Mistakes:
  • Assuming all types have length property
  • Thinking indexing List<Int> is invalid
  • Ignoring type mismatch errors
5. How do generics prevent mixing wrong types in Kotlin collections? Consider this code:
val numbers: MutableList<Number> = mutableListOf(1, 2.5, 3)
numbers.add(4.0f)
numbers.add("five")

What happens and why?
hard
A. Compilation error on adding "five" because it's not a Number
B. All values added successfully, no errors
C. Runtime error when adding 4.0f
D. Compilation error on adding 4.0f because it's a Float

Solution

  1. Step 1: Understand the collection type

    The list is declared as MutableList<Number>, so it accepts any subtype of Number like Int, Double, Float.
  2. Step 2: Check the added elements

    Adding 4.0f (a Float) is allowed because Float is a Number subtype. Adding "five" (a String) causes a compile-time error because String is not a Number.
  3. Final Answer:

    Compilation error on adding "five" because it's not a Number -> Option A
  4. Quick Check:

    Generics block wrong types at compile time [OK]
Hint: Only add types matching generic parameter [OK]
Common Mistakes:
  • Thinking all types can be added to Number list
  • Confusing runtime and compile-time errors
  • Assuming Float is not a Number subtype
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard