androidengineers.Book a session

Functional Programming

Higher-Order Functions & Function Types

article15 minMedium

Pass behavior as a value

A higher-order function accepts a function or returns one. A function type records its parameter and result types; (String) -> Boolean describes a predicate over strings.

fun select(topics: List<String>, accept: (String) -> Boolean): List<String> =
    topics.filter(accept)

fun main() {
    val longEnough: (String) -> Boolean = { it.length >= 6 }
    check(select(listOf("AI", "Kotlin"), longEnough) == listOf("Kotlin"))
}

The selection algorithm owns iteration; the caller owns the acceptance rule. This separation permits tests with deterministic predicates and avoids an inheritance hierarchy for every filter.

A function value can capture mutable state, throw exceptions, or perform I/O. Its type alone does not guarantee purity. Document whether an operation calls the supplied function once, many times, or asynchronously when callers need that guarantee.

Exercise

Implement transformTwice(value, transform) for integers. Verify adding two twice changes three to seven. Then use multiplication to show that behavior comes from the supplied function.

Check: do not confuse (Int) -> Int with () -> Int, which takes no input.

Reference: Higher-order functions

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Higher-Order Functions & Function Types | Kotlin Core Programming | Android Engineers