Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 134 ยท Functions

Higher-Order Functions

Learn Kotlin higher-order functions - passing functions as parameters, returning functions, callable references with ::, bound references, closures and common mistakes, with runnable code.

A higher-order function is a function that takes another function as a parameter, returns a function, or both. That sounds abstract, but you have already used dozens of them: map, filter, repeat, sortedBy and forEach all receive a function and call it at the right moment. The idea is simple and powerful. Instead of hard-coding what to do, you write the surrounding logic once (loop over the items, retry three times, measure the time) and let the caller plug in the part that changes.

This lesson shows how to write your own higher-order functions, how to return functions from functions, and how to turn existing functions, constructors and properties into values with the :: operator. It builds on Lambdas and prepares the ground for Inline Functions and Function Types and Type Aliases.

Functions as parameters

To accept a function, give a parameter a function type such as (Int) -> Int. Inside the function you call it like any other function:

Kotlin A function that takes a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 12, 8 and 16. applyTwice(3) { it * 2 } doubles 3 twice. Because the function is the last parameter, the caller can use the trailing-lambda syntax from the previous lesson. applyTwice does not know or care what the operation does; it only promises to call it twice.

Separating the loop from the decision

The classic use is pulling a repeating pattern out of your code. Suppose you often loop over numbers and collect the ones that pass some test. Write the loop once and take the test as a parameter:

Kotlin Your own filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints [12, 7, 20, 18], [12, 20, 18] and [5, 7, 3]. The last call shows that a lambda can use a variable from its surroundings (limit). That is a closure: the lambda carries the variable with it, even when it is called later from inside another function.

Your keepIf is a simplified version of the standard library's filter. Writing it once shows there is no magic: a higher-order function is an ordinary function whose parameter happens to be callable.

Functions that return functions

A function can also build a function. The returned lambda remembers the values it captured, which makes this a neat way to create configured helpers:

Kotlin Returning a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is 42, 63, Hello, Ada!, Salut, Grace! and 20. Every call to multiplier creates a fresh lambda with its own factor, so double and triple do not interfere. The last line calls the result of multiplier(5) immediately with 4.

This is the idea behind currying and partial application: fix some arguments now, supply the rest later. You rarely need heavy functional machinery in Kotlin, but small factory functions like these are everywhere in real code, for example validators, formatters and comparators.

Composing functions

Because functions are values, you can combine them. Here is a function that glues two functions into one:

Kotlin Composing functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The outputs are 6, false and true. The type parameters A, B, C simply say "the output of the first function must fit the input of the second". Generics get their own chapter starting with Generics; for now read (A) -> B as "a function from A to B".

Callable references with ::

Often the function you want to pass already exists under a name. Writing { x -> isEven(x) } is noise; Kotlin lets you pass the function itself with a callable reference, written ::name:

Kotlin Function references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [2, 4, 6], [2, 4, 6], [ALPHA!, BETA!], true, [5, 4] and [ALPHA, BETA]. A reference to a top-level function is ::isEven. A reference to a member function or property of a class uses the class name: String::length is a function that takes a String and returns its length, so it fits (String) -> Int. The reference and the lambda behave the same; pick whichever reads better. A reference is great when the function already has a good name, a lambda when you need to adjust the arguments.

Kinds of references

There are four things you can refer to:

Reference What it is Function type
::isEven Top-level function (Int) -> Boolean
String::length Member property (unbound) (String) -> Int
"abc"::length Bound reference to one object () -> Int
::Person Constructor (String, Int) -> Person

An unbound reference like String::length needs the receiver as its first argument. A bound reference like text::length has already captured one particular object, so it takes no extra argument:

Kotlin Bound references and constructor references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 12, true, [Person(name=Ada, age=36), Person(name=Alan, age=41)], Person(name=Alan, age=41) and then the two people again, one per line. The constructor reference ::Person becomes a function (String, Int) -> Person, which is exactly what zip needs. Notice lengthOfText.get(): a bound reference to a property is a property object with get(), while a bound reference to a function such as text::isNotEmpty is callable directly.

Overloaded functions can make a reference ambiguous. If ::println is used where the compiler cannot work out which overload you mean, give it a type, as in val printer: (Any) -> Unit = ::println. The expected type picks the overload.

Higher-order functions for control flow

A function parameter can wrap a block of code with behaviour you want to repeat: timing, retrying, logging or cleanup. The caller supplies the interesting part:

Kotlin Retry and timing helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see attempt 1 failed: not ready, attempt 2 failed: not ready, ready on try 3, then start greeting, hello, end greeting. Notice that the parameter in (attempt: Int) -> T has a name. Names in function types are documentation only (they show up in IDE hints), and the lambda can use any name it likes.

Return inside lambdas passed to ordinary functions

A plain return inside a lambda would try to return from the enclosing function, which is only allowed when the called function is inline (more in Inline Functions). For ordinary higher-order functions, use a labeled return to leave only the lambda:

Kotlin
numbers.forEach { if (it < 0) return@forEach; println(it) }

That works for both kinds. The lesson on Lambdas covers return@label in detail.

What a function type really is

Under the hood, a function type like (Int) -> Int is an interface (Function1<Int, Int> on the JVM) and a lambda is an object implementing it. Passing a non-inline lambda therefore allocates an object, and calling it is a virtual call. For most code this is irrelevant, but in a hot loop with millions of calls it can matter. inline functions remove that cost by copying the lambda body into the call site, which is the topic of the next lesson.

Function types can be nullable and can have receivers, and you can store functions in collections:

Kotlin Functions in collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is add(6, 3) = 9, sub(6, 3) = 3, mul(6, 3) = 18, null and unknown operation. A map from names to functions is a tidy replacement for a long when, and it can be extended at run time. To call a nullable function, use ?.invoke(...), because maybe(5) would not compile.

Kotlin Calling a nullable function directly (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects this with main.kt:3:13: error: reference has a nullable type '((Int) -> Int)?'. Use explicit '?.invoke' to make a function-like call instead. Write callback?.invoke(5) instead.

Pitfalls and design notes

  • Do not overuse them. A plain loop is sometimes clearer than a chain of three lambdas. Use a function parameter when callers really need to vary the behaviour.
  • Mind captured mutable state. A lambda that changes a captured var works, but if it runs later or on another thread, the result may surprise you. Prefer returning values.
  • Name your function parameters with a verb phrase (onSuccess, predicate, transform) so call sites read well.
  • Put the function parameter last so callers can use the trailing-lambda syntax.
  • Large pipelines allocate. Each lambda is an object unless the function is inline; the standard library marks map, filter and friends inline for this reason.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes a function a higher-order function?

    A higher-order function is defined by its parameters or return type: it accepts a function, returns a function, or both.
  2. 2. Which type does the callable reference String::length have?

    String::length is unbound, so it needs a String as its first argument and returns an Int.
  3. 3. What is the difference between String::length and text::length?

    A bound reference (text::length) remembers one particular object; an unbound reference (String::length) takes the receiver as an argument.
  4. 4. How do you safely call a variable of type ((Int) -> Int)??

    A nullable function type cannot be called directly. Use ?.invoke(...), which returns null when the function is null.
  5. 5. Why should a function parameter usually be the last parameter?

    When the last parameter is a function, the lambda can be written outside the parentheses, which reads naturally.

Summary

  • A higher-order function takes functions as parameters, returns functions, or both.
  • Give a parameter a function type such as (Int) -> Boolean, and call it like a function.
  • A returned lambda is a closure: it keeps the variables it captured.
  • ::name turns an existing function, constructor or property into a value; Type::member is unbound, object::member is bound.
  • Nullable function types are called with ?.invoke(...).
  • Ordinary lambdas are objects; inline functions avoid that cost.

Next: Inline Functions