Part 10 / Topic 3 of 8
Function references: ::
A function reference points at an existing function by name, usable anywhere a matching function type is expected — no lambda wrapper needed.
fun isHeavy(s: Shipment) = s.weightKg > 1000.0
println("Heavy (function reference): ${SHIPMENTS.filter(::isHeavy).map { it.id }}")
SHIPMENTS.map { it.id }.forEach(::println)
Heavy (function reference): [S-2001, S-2004]
S-2001
S-2002
S-2003
S-2004
A bound reference is tied to a specific object: calc::priceFor already carries calc
inside it, equivalent to { s -> calc.priceFor(s) }. An unbound reference to a member
function takes the receiver as its own first parameter instead —
PriceCalculator::priceFor has type (PriceCalculator, Shipment) -> Double.
Prices at ₹0.35/kg: [420.0, 112.0, 33.3375, 840.0]
Same price via the unbound reference: 420.0
Rebuilt: [(S-3001, Nagpur), (S-3002, Nashik)]
Weights via property reference: [1200.0, 320.0, 95.25, 2400.0]
::Shipment is a constructor reference — a function from its constructor's parameters to a
Shipment — and Shipment::weightKg is a property reference, reading like a function from
a Shipment to its weightKg.
Full program: examples/03_function_references.kt.
Done here? The practice set for Part 10 — including the solutions — is on the part page.