0
0
Kotlinprogramming~10 mins

Trailing lambda convention 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 call the function using the trailing lambda convention.

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

greet() [1] {
    println("Hello!")
}
Drag options to blanks, or click blank then click option'
A()
B() -> Unit
C() ->
D() -> {}
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the parentheses entirely when the function requires them.
Trying to put the lambda inside the parentheses incorrectly.
2fill in blank
medium

Complete the code to define a function that takes a lambda and call it using trailing lambda syntax.

Kotlin
fun repeatAction(times: Int, action: () -> Unit) {
    for (i in 1..times) {
        action()
    }
}

repeatAction(3) [1] {
    println("Hi")
}
Drag options to blanks, or click blank then click option'
A()
B() -> Unit
C() ->
D{}
Attempts:
3 left
💡 Hint
Common Mistakes
Removing the parentheses entirely.
Putting the lambda inside the parentheses incorrectly.
3fill in blank
hard

Fix the error in calling the function with trailing lambda syntax.

Kotlin
fun calculate(operation: (Int, Int) -> Int): Int {
    return operation(5, 3)
}

val result = calculate [1] { (a, b) -> a + b }
println(result)
Drag options to blanks, or click blank then click option'
A[
B(
C{
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of curly braces for the lambda.
Using square brackets or angle brackets.
4fill in blank
hard

Fill both blanks to define and call a function using trailing lambda syntax correctly.

Kotlin
fun operate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}

val sum = operate(4, 5[1] [2] a, b -> a + b)
Drag options to blanks, or click blank then click option'
A,
B)
C{
D]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a comma instead of closing parenthesis before the lambda.
Omitting the closing parenthesis before the trailing lambda.
5fill in blank
hard

Fill all three blanks to create a function call with trailing lambda and print the result.

Kotlin
fun transform(value: Int, operation: (Int) -> Int): Int {
    return operation(value)
}

val result = transform[1] 10[2] [3] x -> x * 2
println(result)
Drag options to blanks, or click blank then click option'
A(
B,
C{
D)
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the closing parenthesis before the trailing lambda.
Using a comma instead of ')' after the argument.