Higher-order Functions (part-I)

Learn about higher-order functions and about anonymous functions in Kotlin.

This is where it gets really interesting, and Kotlin’s efficiency is at full display.

If we look at our earlier example, the val keyword is followed by a variable name, strings. Therefore, we’re basically dealing with a variable declaration, which is then defined by the = and the code that follows.

Recall that strings is a list of objects of the String type:

var lengths = strings.map {it.length}

Now, we call a method named map on it, but that looks a bit strange for Java eyes. You might also think we mistyped curly braces for parentheses. However, what looks like a typo is a very common and extremely elegant Kotlin idiom. However, to explain this, we have to introduce the higher-order functions first.

But to explain this, we have to introduce you to higher-order functions first, if you do not already know them from other languages.

Note: We do not consider lambda expressions from Java 8—a fully adequate equivalent.

Higher-order functions

A higher-order function is a function that returns and/or accepts other function(s) as arguments. This means that you can pass one function to another as an argument in Kotlin — and that is exactly what we do in our example.

The map method is part of strings, instead of its type, List<String>, in Kotlin. This is called the extension function of the Iterable<T> type. Such extension functions are another very efficient concept in Kotlin. However, introducing them right here would be too distracting, so we’ll discuss these later.

Therefore, you can call map on strings. If you have not already encountered it in Java 8+, you’ll ask yourself, “What’s map doing anyway?”

Get hands-on with 1400+ tech skills courses.