Lambdas and higher-order functions
Lambdas and higher-order functions
A teacher wants to apply different score corrections without copying the list-processing loop. A higher-order function accepts another function as a value, so the traversal and the correction policy can be expressed separately. A lambda supplies the policy used for each score.
What you’ll learn
- Pass a lambda through a function type.
- Identify captured values and their lifetime.
Lambdas and higher-order functions in the example
Input list
Supply the same rule for each original score.
[70, 80]Captured rule
The lambda adds its captured bonus.
score + 5New result
Map stores returned values in a separate list.
[75, 85]
Understand lambdas and higher-order functions
A higher-order function accepts another function or returns one. A lambda supplies behaviour as a value. It can capture surrounding values, so changing captured mutable state can change behaviour later. A trailing lambda can appear outside parentheses when it is the final argument.
Follow lambdas and higher-order functions
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun adjust(scores: List<Int>, rule: (Int) -> Int): List<Int> = scores.map(rule)
fun main() {
val bonus = 5
println(adjust(listOf(70, 80)) { score -> score + bonus })
}Expected output
[75, 85]Follow the execution
The function type takes one Int and returns an Int. Each score is passed to the lambda, which captures bonus five and returns a corrected mark. Adjust returns [75, 85] without changing the input list.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Lambdas and higher-order functions
Your task: Why can the lambda use bonus even though it is not its parameter?
Kotlin/JVM · complete program
fun adjust(scores: List<Int>, rule: (Int) -> Int): List<Int> = scores.map(rule)
fun main() {
val bonus = 5
println(adjust(listOf(70, 80)) { score -> score + bonus })
}Worked answer
The lambda captures the surrounding value. Its parameter supplies each score, while bonus comes from the enclosing scope.
Lambdas and higher-order functions: the important boundary
Lambda return rules differ between local labelled returns and non-local returns permitted by particular inline calls. Use clear labels when needed. Captured mutable state is not automatically safe for concurrent use.
Check your understanding
Lambdas and higher-order functions: what to keep in mind
The lambda captures the surrounding value. Its parameter supplies each score, while bonus comes from the enclosing scope. Lambda return rules differ between local labelled returns and non-local returns permitted by particular inline calls.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.