Higher-Order Functions

Functions that Take Functions

A higher-order function takes a function as a parameter or returns one. filter, map and forEach are all higher-order functions. You can write your own to remove repeated code.

Example

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int = operation(a, b)

fun repeatTask(times: Int, task: (Int) -> Unit) {
    for (i in 1..times) task(i)
}

fun main() {
    println(calculate(10, 5) { x, y -> x + y })
    println(calculate(10, 5) { x, y -> x * y })
    repeatTask(3) { println("Attempt $it") }
}

Output

15
50
Attempt 1
Attempt 2
Attempt 3

Functions that Return Functions

Example

fun discount(percent: Int): (Double) -> Double = { price -> price - price * percent / 100 }

fun main() {
    val diwaliSale = discount(30)
    val clearance = discount(50)
    println(diwaliSale(1000.0))
    println(clearance(1000.0))
}

Output

700.0
500.0

Exercise

Exercise: Write fun applyTwice(x: Int, f: (Int) -> Int): Int that applies f two times. applyTwice(3) { it * 10 } should be 300.

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

fun main() {
    println(applyTwice(3) { it * 10 }) // 300
}