0
0
Kotlinprogramming~20 mins

Returning functions from functions in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Returning Functions
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code returning a function?

Look at this Kotlin code that returns a function. What will it print?

Kotlin
fun makeMultiplier(x: Int): (Int) -> Int {
    return { y -> x * y }
}

fun main() {
    val multiplyBy3 = makeMultiplier(3)
    println(multiplyBy3(5))
}
A15
B8
C35
DCompilation error
Attempts:
2 left
💡 Hint

Remember the returned function multiplies its input by the captured value.

🧠 Conceptual
intermediate
2:00remaining
Which Kotlin function type correctly represents a function returning a function?

Which of these Kotlin function types correctly describes a function that returns another function taking an Int and returning a String?

A(Int) -> Int -> String
B(Int) -> (String) -> Int
C(Int) -> (Int, String) -> String
D(Int) -> (Int) -> String
Attempts:
2 left
💡 Hint

Remember to use parentheses to group function types properly.

🔧 Debug
advanced
2:00remaining
What error does this Kotlin code produce?

Consider this Kotlin code that tries to return a function. What error will it cause?

Kotlin
fun getAdder(x: Int): (Int) -> Int {
    return { y -> x + y }
}

fun main() {
    val add5 = getAdder(5)
    println(add5(10))
}
ASyntax error: unexpected token '->' in return type
BRuntime error: NullPointerException
CNo error, prints 15
DCompilation error: Type mismatch in return statement
Attempts:
2 left
💡 Hint

Check the syntax for function types in Kotlin return types.

🚀 Application
advanced
2:00remaining
How many times is the inner function called in this Kotlin code?

Analyze this Kotlin code that returns a function and calls it multiple times. How many times is the inner function executed?

Kotlin
fun counter(): () -> Int {
    var count = 0
    return {
        count += 1
        count
    }
}

fun main() {
    val c = counter()
    println(c())
    println(c())
    println(c())
}
A1
B3
C0
DCompilation error
Attempts:
2 left
💡 Hint

Each call to c() runs the inner function once.

Predict Output
expert
2:00remaining
What is the output of this Kotlin code with nested returned functions?

Examine this Kotlin code with nested functions returned from functions. What will it print?

Kotlin
fun outer(x: Int): (Int) -> (Int) -> Int {
    return { y -> { z -> x + y + z } }
}

fun main() {
    val f = outer(1)
    val g = f(2)
    println(g(3))
}
A5
B9
C6
DCompilation error
Attempts:
2 left
💡 Hint

Trace the values captured by each returned function.