Interview QuestionPractical QuestionFollow-up Questions

Higher Order Functions in Kotlin

skydovesJaewoong Eum (skydoves)||7 min read

Higher Order Functions in Kotlin

A higher order function is a function that takes another function as a parameter, returns a function, or both. This concept is central to Kotlin's support for functional programming and enables patterns such as callbacks, collection transformations, and domain specific language construction. Higher order functions allow behavior to be passed as data, making code more modular, reusable, and expressive. By the end of this lesson, you will be able to:

  • Define higher order functions that accept function type parameters.
  • Implement functions that return other functions for dynamic behavior composition.
  • Explain how lambdas and function references are used as arguments to higher order functions.
  • Identify standard library higher order functions and their use in collection processing.

Accepting Functions as Parameters

A higher order function declares one or more parameters with a function type. Function types in Kotlin are expressed as (InputTypes) -> ReturnType.

fun operate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}

The operation parameter is a function that takes two Int values and returns an Int. The caller provides the actual behavior:

val sum = operate(3, 4) { a, b -> a + b }
val product = operate(3, 4) { a, b -> a * b }

The lambda expression { a, b -> a + b } is passed as the operation argument. Kotlin's trailing lambda syntax allows the lambda to appear outside the parentheses when it is the last parameter.

Returning Functions

A higher order function can also return a function, enabling dynamic behavior composition:

fun multiplier(factor: Int): (Int) -> Int {
    return { value -> value * factor }
}

val triple = multiplier(3)
println(triple(5))  // Output: 15

The multiplier function captures the factor parameter in a closure and returns a new function that uses it. Each call to multiplier with a different factor produces a distinct function.

Function References

Instead of lambdas, existing named functions can be passed using the :: reference syntax:

fun isEven(n: Int): Boolean = n % 2 == 0

val evenNumbers = listOf(1, 2, 3, 4, 5).filter(::isEven)

This interview continues for subscribers

Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.

Become a Sponsor