Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 10 / Topic 2 of 8

Higher-order functions and function types

A higher-order function is one that takes a function as a parameter, returns a function, or both. The parameter's type is a function signature — (Shipment) -> Boolean reads as "a function from Shipment to Boolean" — not a class name.

fun select(shipments: List<Shipment>, rule: (Shipment) -> Boolean): List<String> =
    shipments.filter(rule).map { it.id }

fun heavierThan(thresholdKg: Double): (Shipment) -> Boolean = { it.weightKg > thresholdKg }
Delayed: [S-2002, S-2004]
From Pune: [S-2001, S-2003]
Over 1000 kg: [S-2001, S-2004]
Delayed AND over 300 kg: [S-2002, S-2004]

heavierThan(1000.0) returns a function with 1000.0 already captured inside it — call it later and that threshold is still there. Functions as values also compose: combine(a, b) below builds a brand-new (Shipment) -> Boolean out of two existing ones, by wrapping them in a lambda that calls both.

Full program: examples/02_higher_order_functions.kt.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide