0
0
Kotlinprogramming~10 mins

Why functions are first-class in Kotlin - Test Your Understanding

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

Complete the code to declare a function variable that adds two numbers.

Kotlin
val add: (Int, Int) -> Int = [1]
Drag options to blanks, or click blank then click option'
A{ a, b -> a + b }
Bfun add(a: Int, b: Int): Int = a + b
Ca + b
Dlambda(a, b) { a + b }
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign a function declaration instead of a lambda.
Using incorrect syntax like 'lambda' keyword which doesn't exist in Kotlin.
2fill in blank
medium

Complete the code to pass a function as a parameter.

Kotlin
fun operate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return [1](x, y)
}
Drag options to blanks, or click blank then click option'
Ay
Boperation
Cx
Doperate
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call the function by its own name instead of the parameter.
Using variables x or y as if they were functions.
3fill in blank
hard

Fix the error in the code to assign a function reference to a variable.

Kotlin
fun greet(name: String) = "Hello, $name"

val greeter: (String) -> String = [1]
Drag options to blanks, or click blank then click option'
A::greet
Bgreet.name
Cgreet()
Dgreet{}
Attempts:
3 left
💡 Hint
Common Mistakes
Adding parentheses which calls the function instead of referencing it.
Using invalid syntax like greet.name or greet{}.
4fill in blank
hard

Fill both blanks to create a list of functions and call the first one.

Kotlin
val functions = listOf<(Int) -> Int>({ x -> x * 2 }, [1])

val result = functions[0]([2])
println(result)
Drag options to blanks, or click blank then click option'
A{ x -> x + 3 }
B5
C10
D{ y -> y - 1 }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a function call instead of a lambda as the second list element.
Using a function call or variable instead of an integer argument.
5fill in blank
hard

Fill all three blanks to filter and map a list using functions.

Kotlin
val numbers = listOf(1, 2, 3, 4, 5)

val filtered = numbers.filter [1] 
val mapped = filtered.map [2] 

println(mapped) // Output: [3]
Drag options to blanks, or click blank then click option'
A{ it > 2 }
B{ it * 10 }
C[30, 40, 50]
D{ it < 3 }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong filter condition like less than 3.
Mapping with addition instead of multiplication.
Expecting wrong output list.