Higher-Order Functions
Functions that take other functions as parameters or return a function as their result.
fun process(data: List<Int>, operation: (Int) -> Int): List<Int> { ... }
fun createMultiplier(factor: Int): (Int) -> Int { ... }This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Functions that take other functions as parameters or return a function as their result.
Higher-order functions are a cornerstone of functional programming in Kotlin, enabling powerful abstractions and more expressive code. They treat functions as first-class citizens, meaning functions can be stored in variables, passed as arguments to other functions, and returned as results from other functions. This capability allows for the creation of highly flexible and reusable code, as behavior can be abstracted and injected dynamically. Common examples in the Kotlin standard library include collection operations like `map`, `filter`, and `forEach`, which accept a lambda (a function literal) to define the specific action to perform on each element. When declaring a higher-order function, you specify the 'function type' for its parameters or return value (e.g., `(Int) -> String` for a function that takes an `Int` and returns a `String`, or `() -> Unit` for a function with no parameters and no meaningful return value). Higher-order functions are instrumental in building domain-specific languages (DSLs), event handling, and creating flexible APIs that adapt to various use cases, promoting a more declarative and less imperative coding style.
Quick reference
Syntax
fun process(data: List<Int>, operation: (Int) -> Int): List<Int> { ... }
fun createMultiplier(factor: Int): (Int) -> Int { ... }
Inputs
Parameters
See it in practice
Examples
Function taking another function as a parameter
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val sum = calculate(10, 5) { x, y -> x + y }
val difference = calculate(10, 5) { x, y -> x - y }
println("Sum: $sum, Difference: $difference")Sum: 15, Difference: 5
The `calculate` function takes two integers and a lambda `operation` (a function type `(Int, Int) -> Int`) to perform a calculation.
Function returning another function
fun getMultiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}
val multiplyByTwo = getMultiplier(2)
val multiplyByTen = getMultiplier(10)
println("5 * 2 = ${multiplyByTwo(5)}")
println("5 * 10 = ${multiplyByTen(5)}")5 * 2 = 10 5 * 10 = 50
The `getMultiplier` function returns a new lambda function that multiplies its input by the given `factor`.
Using standard library higher-order functions
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
val squaredNumbers = numbers.map { it * it }
println("Even numbers: $evenNumbers")
println("Squared numbers: $squaredNumbers")Even numbers: [2, 4] Squared numbers: [1, 4, 9, 16, 25]
Common collection functions like `filter` and `map` are higher-order functions that take a lambda to define their behavior.
Debug faster
Common Errors
Function Type Mismatch
Cause: The lambda or function passed as an argument does not match the expected function type signature (e.g., wrong number of parameters, incorrect parameter types, or incompatible return type).
Fix: Carefully check the function type signature defined in the higher-order function's parameters. Ensure the lambda you provide has the correct number and types of parameters and returns the expected type.
fun processString(op: (String) -> Unit) { op("data") }
processString { num: Int -> println(num) } // Error: Type mismatch, expected (String) -> UnitRuntime support
Compatibility
Source: Kotlin Documentation
Common questions
Frequently Asked Questions
Functions that take other functions as parameters or return a function as their result.
functionParameter: A function type representing a function passed as an argument. returnFunction: A function type representing a function returned as a result.
Function Type Mismatch: Carefully check the function type signature defined in the higher-order function's parameters. Ensure the lambda you provide has the correct number and types of parameters and returns the expected type.