Higher-Order Functions and Lambdas
Higher-Order Functions and Lambdas
Higher-Order Functions
A higher-order function is a function that takes functions as parameters, or returns a function. A good example of such a function is lock()
that takes a lock object and a function, acquires the lock, runs the function and releases the lock:
fun <T> lock(lock: Lock, body: () -> T): T { lock.lock() try { return body() } finally { lock.unlock() } }
Let's examine the code above: body
has a function type: () -> T
, so it's supposed to be a function that takes no parameters and returns a value of type T
. It is invoked inside the try-block, while protected by the lock
, and its result is returned by the lock()
function.
If