As we discussed previously, in Kotlin, it's possible for a function to return another function:
fun generateMultiply(): (Int, Int) -> Int {
return { x: Int, y: Int -> x * y}
}
Functions can also be assigned to a variable or value to be invoked later on:
val multiplyFunction = generateMultiply()
...
println(multiplyFunction(3, 4))
The function assigned to a variable is usually called a literal function. It's also possible to specify a function as a parameter:
fun mathInvoker(x: Int, y: Int, mathFunction: (Int, Int) -> Int) {
println(mathFunction(x, y))
}
mathInvoker(5, 6, multiplyFunction)
If a function is the last parameter, it can also be supplied ad hoc, outside of the brackets:
mathInvoker(7, 8) { x, y ->
x * y
}
In general, a function without a name is called an anonymous function. If a function without a name uses short syntax, it's called a lambda:
val squareAnonymous = fun(x: Int) = x * x
val squareLambda = {x: Int -> x * x}