Challenge - 5 Problems
Higher-order Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple higher-order function call
What is the output of this Kotlin code that uses a higher-order function?
Kotlin
fun operateOnNumber(x: Int, operation: (Int) -> Int): Int { return operation(x) } fun main() { val result = operateOnNumber(5) { it * 3 } println(result) }
Attempts:
2 left
💡 Hint
Look at how the lambda multiplies the input by 3.
✗ Incorrect
The function operateOnNumber takes an integer and a function that transforms an integer. The lambda multiplies 5 by 3, so the output is 15.
🧠 Conceptual
intermediate1:30remaining
Understanding function types in Kotlin
Which of the following is the correct Kotlin function type declaration for a function that takes a String and returns a Boolean?
Attempts:
2 left
💡 Hint
Function types use the arrow notation with parentheses around parameters.
✗ Incorrect
In Kotlin, function types are declared as (ParameterType) -> ReturnType. So a function taking a String and returning a Boolean is (String) -> Boolean.
🔧 Debug
advanced2:00remaining
Identify the error in this higher-order function declaration
What error does this Kotlin code produce?
Kotlin
fun applyTwice(x: Int, f: (Int) -> Int): Int { return f(f(x)) } fun main() { println(applyTwice(2) { it + 3 }) }
Attempts:
2 left
💡 Hint
Check the function type syntax in the parameter list.
✗ Incorrect
The function type parameter must be declared with parentheses around the parameter type: (Int) -> Int, not Int -> Int.
❓ Predict Output
advanced2:30remaining
Output of nested higher-order functions
What is the output of this Kotlin code?
Kotlin
fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int { return { x -> f(g(x)) } } fun main() { val add2 = { x: Int -> x + 2 } val times3 = { x: Int -> x * 3 } val combined = compose(add2, times3) println(combined(4)) }
Attempts:
2 left
💡 Hint
Remember the order of function composition: f(g(x)) means g runs first.
✗ Incorrect
times3(4) = 12, then add2(12) = 14, so the output is 14.
🧠 Conceptual
expert1:30remaining
Effect of inline keyword on higher-order functions
What is the main benefit of declaring a higher-order function as inline in Kotlin?
Attempts:
2 left
💡 Hint
Think about performance and how lambdas are handled at runtime.
✗ Incorrect
Inlining a higher-order function copies the function body at call sites, avoiding lambda object creation and improving performance.