0
0
Kotlinprogramming~10 mins

Passing lambdas to functions in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to pass a lambda that prints "Hello".

Kotlin
fun greet(action: () -> Unit) {
    action()
}

greet([1])
Drag options to blanks, or click blank then click option'
A-> println("Hello")
Bprintln("Hello")
Cfun() { println("Hello") }
D{ println("Hello") }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing println("Hello") directly without braces.
Using incorrect lambda syntax like '-> println("Hello")'.
2fill in blank
medium

Complete the code to pass a lambda that returns the sum of two integers.

Kotlin
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val result = operate(3, 4, [1])
println(result)
Drag options to blanks, or click blank then click option'
A{ x, y -> x + y }
B{ x, y -> x - y }
C{ x, y -> x * y }
D{ x, y -> x / y }
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction, multiplication, or division instead of addition.
Incorrect lambda parameter syntax.
3fill in blank
hard

Fix the error in passing a lambda that prints the given message.

Kotlin
fun printMessage(message: String, action: (String) -> Unit) {
    action(message)
}

printMessage("Hi", [1])
Drag options to blanks, or click blank then click option'
A{ println(it) }
B{ msg -> println(msg) }
Cprintln
D{ msg -> print(msg) }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing println directly without matching the parameter.
Using { println(it) } without specifying the parameter name.
4fill in blank
hard

Fill both blanks to create a lambda that filters even numbers and doubles them.

Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.filter([1]).map([2])
println(result)
Drag options to blanks, or click blank then click option'
A{ it % 2 == 0 }
B{ it * 2 }
C{ it % 2 != 0 }
D{ it + 2 }
Attempts:
3 left
💡 Hint
Common Mistakes
Filtering odd numbers instead of even.
Adding 2 instead of multiplying by 2 in map.
5fill in blank
hard

Fill all three blanks to create a lambda that sorts strings by length and filters those longer than 3.

Kotlin
val words = listOf("cat", "house", "dog", "elephant")
val filtered = words.sortedBy([1]).filter([2]).map([3])
println(filtered)
Drag options to blanks, or click blank then click option'
A{ it.length }
B{ it.length > 3 }
C{ it.uppercase() }
D{ it.length < 3 }
Attempts:
3 left
💡 Hint
Common Mistakes
Filtering words shorter than 3 instead of longer.
Not converting words to uppercase in map.