Introduction
Sometimes you want a function to create and give you another function to use later. This helps keep your code neat and flexible.
Sometimes you want a function to create and give you another function to use later. This helps keep your code neat and flexible.
fun outerFunction(): (Int) -> Int { return fun(innerValue: Int): Int { return innerValue * 2 } }
The outer function returns another function as its result.
The returned function can take parameters and return a value.
fun makeMultiplier(factor: Int): (Int) -> Int { return { number -> number * factor } }
fun greeter(name: String): () -> String { return { "Hello, $name!" } }
This program creates a function that adds 5 to any number. Then it uses that function to add 5 to 10 and 3.
fun makeAdder(x: Int): (Int) -> Int { return { y -> x + y } } fun main() { val addFive = makeAdder(5) println(addFive(10)) println(addFive(3)) }
You can use lambda expressions to return functions easily.
Returned functions can capture variables from the outer function (called closures).
Functions can return other functions to create flexible and reusable code.
Returned functions can take parameters and use values from the outer function.
fun makeMultiplier(x: Int): (Int) -> Int {
return { y -> x * y }
}
fun main() {
val multiplyBy3 = makeMultiplier(3)
println(multiplyBy3(5))
}fun outer(): (Int) -> Int {
val inner = { x: Int -> x * 2 }
return inner()
}fun createCounter(start: Int): () -> Int {
var count = start
return {
count += 1
count
}
}
fun main() {
val counter = createCounter(10)
println(counter())
println(counter())
}Pass the test and this pattern moves unknown