Lesson 15 of 17

Higher-Order Functions

Higher-Order Functions

A higher-order function takes a function as a parameter or returns one. Function types look like (Int) -> Int:

fun applyTwice(f: (Int) -> Int, x: Int): Int = f(f(x))

val double = { n: Int -> n * 2 }
println(applyTwice(double, 3))  // 12

This enables powerful abstractions. You can chain list operations:

val result = listOf(1, 2, 3, 4, 5)
    .filter { it % 2 != 0 }
    .map { it * it }
// [1, 9, 25]

Higher-order functions are at the heart of functional programming.

Your Turn

Write a function applyTwice(f: (Int) -> Int, x: Int): Int that applies f to x twice. Then use it with a tripling function to compute applyTwice(triple, 2) and applyTwice(triple, 4).

JS Transpiler loading...
Loading...
Click "Run" to execute your code.