0
0
Kotlinprogramming~20 mins

Passing lambdas to functions in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Lambda Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a lambda passed to a function
What is the output of this Kotlin code when the lambda is passed to the function?
Kotlin
fun operateOnNumber(x: Int, operation: (Int) -> Int): Int {
    return operation(x)
}

fun main() {
    val result = operateOnNumber(5) { it * 3 }
    println(result)
}
A8
B15
CCompilation error
D5
Attempts:
2 left
💡 Hint
Remember that the lambda multiplies the input by 3.
Predict Output
intermediate
2:00remaining
Lambda with multiple parameters
What will be printed by this Kotlin program?
Kotlin
fun combineStrings(a: String, b: String, combiner: (String, String) -> String): String {
    return combiner(a, b)
}

fun main() {
    val result = combineStrings("Hello", "World") { x, y -> "$x $y!" }
    println(result)
}
AHello World!
BHelloWorld!
CHello World
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the lambda formats the strings with a space and exclamation mark.
🔧 Debug
advanced
2:00remaining
Identify the error when passing a lambda
This Kotlin code does not compile. What is the cause of the error?
Kotlin
fun applyOperation(x: Int, operation: (Int) -> Int): Int {
    return operation(x)
}

fun main() {
    val result = applyOperation(10) { it + 5 }
    println(result)
}
AType mismatch: lambda parameter type should be (Int) -> Int
BSyntax error: missing parentheses around lambda parameter type
CRuntime exception: null pointer
DNo error, code compiles and runs
Attempts:
2 left
💡 Hint
Check the function parameter type declaration syntax for lambdas.
Predict Output
advanced
2:00remaining
Lambda capturing external variable
What is the output of this Kotlin code?
Kotlin
fun main() {
    var counter = 0
    val increment: () -> Int = { counter += 1; counter }
    println(increment())
    println(increment())
    println(counter)
}
ACompilation error
B
0
1
2
C
1
1
1
D
1
2
2
Attempts:
2 left
💡 Hint
The lambda modifies the external variable counter each time it is called.
🧠 Conceptual
expert
2:00remaining
Effect of inline lambdas on performance
Which statement about inline lambdas in Kotlin is true?
AInline lambdas cannot capture variables from the outer scope.
BInlining lambdas always increases the size of the compiled code without any performance benefit.
CInlining lambdas reduces runtime overhead by avoiding object allocation and call overhead.
DInlining lambdas disables the use of return statements inside the lambda.
Attempts:
2 left
💡 Hint
Think about how inlining affects function calls and memory allocation.