Higher-order functions

A function is called higher-order if it can take or return another function. The following diagrams show the different cases of higher-order functions.

The first diagram demonstrates a case in which the f function takes the lambda and returns a simple object:

The second diagram demonstrates a case in which the f function takes an object and returns a function:

Finally, the third diagram demonstrates a case in which the f function takes and returns lambdas:

Let's look at the implementation of the firstOrNull function, as follows:

public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}

The firstOrNull function is an extension that takes a lambda as a parameter and invokes it as the usual function—predicate(element). This returns the first element that matches the predicate in a collection; it is null if there is no other element that meets a condition.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.215.96