Look at this Kotlin code that returns a function. What will it print?
fun makeMultiplier(x: Int): (Int) -> Int { return { y -> x * y } } fun main() { val multiplyBy3 = makeMultiplier(3) println(multiplyBy3(5)) }
Remember the returned function multiplies its input by the captured value.
The function makeMultiplier returns a function that multiplies its input by x. Here, x is 3, so calling multiplyBy3(5) returns 3 * 5 = 15.
Which of these Kotlin function types correctly describes a function that returns another function taking an Int and returning a String?
Remember to use parentheses to group function types properly.
In Kotlin, a function returning a function is written as (InputType) -> (ReturnedFunctionType). Here, the returned function takes an Int and returns a String, so the full type is (Int) -> (Int) -> String.
Consider this Kotlin code that tries to return a function. What error will it cause?
fun getAdder(x: Int): (Int) -> Int { return { y -> x + y } } fun main() { val add5 = getAdder(5) println(add5(10)) }
Check the syntax for function types in Kotlin return types.
The return type Int -> Int is invalid syntax in Kotlin. The correct syntax uses parentheses: (Int) -> Int. The arrow must be inside parentheses to denote a function type.
Analyze this Kotlin code that returns a function and calls it multiple times. How many times is the inner function executed?
fun counter(): () -> Int { var count = 0 return { count += 1 count } } fun main() { val c = counter() println(c()) println(c()) println(c()) }
Each call to c() runs the inner function once.
The function counter returns a function that increments and returns count. Each call to c() runs this inner function, so it is called 3 times.
Examine this Kotlin code with nested functions returned from functions. What will it print?
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)) }
Trace the values captured by each returned function.
The outer function returns a function that takes y and returns another function taking z. The final sum is x + y + z. Here, x=1, y=2, z=3, so the output is 6.