Search⌘ K

Higher-order Functions (part-I)

Explore the concept of higher-order functions in Kotlin, including how functions can be passed as arguments to other functions. Understand the map function as a core example, and see how Kotlin enables concise and expressive transformations on collections by using anonymous function references. Gain familiarity with Kotlin’s approach compared to Java to improve your coding efficiency.

We'll cover the following...

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 ...