Challenge - 5 Problems
Kotlin Type Inference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code with type inference?
Consider the following Kotlin code snippet. What will be printed when it runs?
Kotlin
fun main() { val x = listOf(1, 2, 3).map { it * 2 } println(x) }
Attempts:
2 left
💡 Hint
The map function applies the lambda to each element, doubling it.
✗ Incorrect
The listOf creates a list of integers. The map function multiplies each element by 2, so the output list is [2, 4, 6].
❓ Predict Output
intermediate2:00remaining
What type does the compiler infer for this variable?
Given the Kotlin code below, what is the inferred type of variable
result?Kotlin
val result = listOf("apple", "banana", "cherry").filter { it.startsWith('b') }
Attempts:
2 left
💡 Hint
The filter function returns the same collection type as the original list but filtered.
✗ Incorrect
The filter function returns a List because the original collection is a List and filter preserves the type.
🔧 Debug
advanced2:00remaining
What error does this Kotlin code produce due to type inference?
Examine the Kotlin code below. What error will the compiler report?
Kotlin
fun main() { val x = null println(x) }
Attempts:
2 left
💡 Hint
Kotlin requires explicit type for null without context.
✗ Incorrect
The compiler cannot infer the type of x because null has no type by itself. Kotlin requires explicit type declaration for null values.
❓ Predict Output
advanced2:00remaining
What is the output of this Kotlin code using type inference with lambdas?
What will this Kotlin program print when executed?
Kotlin
fun main() { val numbers = listOf(1, 2, 3, 4) val doubled = numbers.map { it * 2 } val filtered = doubled.filter { it > 4 } println(filtered) }
Attempts:
2 left
💡 Hint
First double each number, then keep only those greater than 4.
✗ Incorrect
The map doubles each number: [2,4,6,8]. The filter keeps numbers > 4: [6,8].
🧠 Conceptual
expert3:00remaining
Which statement about Kotlin's type inference is correct?
Choose the correct statement about how Kotlin infers types in the following scenario.
Kotlin
val x = listOf(1, 2, 3).map { if (it % 2 == 0) it else "odd" }
Attempts:
2 left
💡 Hint
Kotlin infers the closest common supertype when lambda returns different types.
✗ Incorrect
Since the lambda returns Int for even numbers and String for odd numbers, Kotlin infers List as the common supertype.