๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Higher-Order Functions

A higher-order function takes a function as a parameter or returns a function as its result. Programs use it to pass behavior into a shared task.

A function that takes a function

operate receives a value and a function, then runs the function on the value. The lambda inside the call doubles as the changing part.

fun operate(value: Int, op: (Int) -> Int): Int {
    return op(value)
}

fun main() {
    val result = operate(5, { x -> x * 3 })
    println(result)
}

A function that returns a function

makeMultiplier builds a lambda that multiplies by the factor it was given. The returned value is a working function.

fun makeMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

fun main() {
    val triple = makeMultiplier(3)
    println(triple(4))
    println(triple(10))
}

Passing a stored function value

The variable addTwo holds a function value. Passing its name hands the whole function to applyTwice.

fun applyTwice(value: Int, op: (Int) -> Int): Int {
    return op(op(value))
}

fun main() {
    val addTwo: (Int) -> Int = { x -> x + 2 }
    println(applyTwice(3, addTwo))
}

Example

fun calculate(a: Int, b: Int, op: (Int, Int) -> Int): Int {
    return op(a, b)
}

fun main() {
    val multiply: (Int, Int) -> Int = { x, y -> x * y }
    println(calculate(6, 7, multiply))
    println(calculate(6, 7, { x, y -> x + y }))
}

Key points

  • A function parameter is written with a function type in the parameter list.
  • The body runs the parameter by its name, like a local function.
  • A function can return a lambda as its result.
  • The returned lambda remembers the values from the call that made it.
  • Pass a stored function value by its name, with no parentheses after the name.

In this example, calculate runs whatever function it receives on its two numbers. The first call passes the stored multiply value and prints 42. The second call passes a lambda that adds, and it prints 13.

Note

A lambda passed as an argument sits inside the call parentheses in this lesson.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What makes a function a higher-order function?