Higher-Order Function (Kotlin)

A higher-order function is one that takes another function as a parameter or returns a function. Kotlin treats functions as first-class values, which powers its expressive collection and DSL APIs.

Kotlin

Because functions are first-class, you can pass them around as arguments and return them. A parameter typed (Int) -> Int accepts any function or lambda matching that signature. This is what lets filter, map, fold, and friends take behavior as a parameter.

You pass behavior in as a lambda, and Kotlin's trailing-lambda syntax lets you move a final function argument outside the parentheses, giving the clean list.filter { it > 0 } reads-like-English style. The convention it names the single parameter of a lambda.

Higher-order functions enable functional composition, callbacks, and DSLs. Marking one inline removes the lambda's object-allocation overhead by inlining its body at the call site — important for hot loops.

Syntax

fun apply(x: Int, op: (Int) -> Int): Int = op(x)

Examples

Kotlin

fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))
println(applyTwice(3) { it + 1 })

Output:

5

Learn it in a lesson

See also

Back to the Dictionary