Challenge - 5 Problems
Generic Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple generic function
What is the output of this Kotlin code that uses a generic function to return the input value?
Kotlin
fun <T> identity(value: T): T { return value } fun main() { println(identity(42)) }
Attempts:
2 left
💡 Hint
Think about what the function returns when given an integer.
✗ Incorrect
The generic function identity returns the same value it receives. Here, it returns 42, so the output is 42.
🧠 Conceptual
intermediate1:30remaining
Understanding generic function type parameters
In Kotlin, what does the in the function declaration fun echo(item: T): T mean?
Attempts:
2 left
💡 Hint
Generic type parameters allow flexibility in the function input and output types.
✗ Incorrect
The declares a generic type parameter named T. This means the function can accept and return any type specified when called.
❓ Predict Output
advanced2:00remaining
Output of generic function with multiple types
What is the output of this Kotlin code that uses a generic function with two type parameters?
Kotlin
fun <A, B> pairToString(a: A, b: B): String { return "$a and $b" } fun main() { println(pairToString(10, "apples")) }
Attempts:
2 left
💡 Hint
Look at how the function combines the two parameters into a string.
✗ Incorrect
The function takes two generic parameters and returns a string combining them. Here it prints "10 and apples".
🔧 Debug
advanced2:00remaining
Identify the error in this generic function declaration
What error does this Kotlin code produce?
fun printTwice(value: T) {
println(value)
println(value)
}
fun main() {
printTwice()
}
Kotlin
fun <T> printTwice(value: T) { println(value) println(value) } fun main() { printTwice() }
Attempts:
2 left
💡 Hint
Check the function call and its parameters.
✗ Incorrect
The function requires one argument of type T, but the call provides none, causing a compilation error.
🚀 Application
expert2:30remaining
Result of generic function with nullable type and default value
What is the output of this Kotlin code that uses a generic function with a nullable type and a default value?
Kotlin
fun <T> defaultIfNull(value: T?, default: T): T { return value ?: default } fun main() { println(defaultIfNull(null, "Hello")) println(defaultIfNull("World", "Hello")) }
Attempts:
2 left
💡 Hint
The Elvis operator ?: returns the left value if not null, otherwise the right value.
✗ Incorrect
The function returns the default value if the input is null. So first line prints "Hello", second prints "World".