0
0
Kotlinprogramming~20 mins

Type inference by the compiler in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Type Inference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
A[2, 4, 6]
B[1, 2, 3]
C[1, 4, 9]
DCompilation error
Attempts:
2 left
💡 Hint
The map function applies the lambda to each element, doubling it.
Predict Output
intermediate
2: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') }
AMutableList<String>
BList<String>
CSet<String>
DArray<String>
Attempts:
2 left
💡 Hint
The filter function returns the same collection type as the original list but filtered.
🔧 Debug
advanced
2: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)
}
AType inference error: Null can not be a value of a non-null type
BRuntime NullPointerException
CCompilation succeeds and prints 'null'
DSyntax error: missing type declaration
Attempts:
2 left
💡 Hint
Kotlin requires explicit type for null without context.
Predict Output
advanced
2: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)
}
A[1, 2, 3, 4]
B[2, 4]
C[6, 8]
DCompilation error due to type mismatch
Attempts:
2 left
💡 Hint
First double each number, then keep only those greater than 4.
🧠 Conceptual
expert
3: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" }
AThe inferred type of x is List<String> because of the else branch
BThe inferred type of x is List<Int> because all elements are numbers
CThe code causes a compilation error due to mixed types in the lambda
DThe inferred type of x is List<Any> because the lambda returns Int or String
Attempts:
2 left
💡 Hint
Kotlin infers the closest common supertype when lambda returns different types.