KOTLIN / CHAPTER 08
Higher-order functions and captured state
AdvancedTrace functions as values and make closure state explicit.
By the end of this chapter
- Pass behavior as a parameter
- Trace captured local state
- Separate pure transformations from side effects
The idea
A higher-order function accepts another function or returns one. A function type such as (Int) -> Boolean describes the input and result needed by a caller. Supplying a predicate separates a traversal algorithm from the rule that selects values. Keep the predicate’s intended behavior clear: a stateful predicate can make repeated traversals behave differently even when the input collection is unchanged.
A lambda can capture local variables from its surrounding scope. A factory that declares a counter and returns a lambda creates one retained state per factory call. Assigning that lambda to another variable shares the same closure; it does not run the factory again. Prefer pure transformations when repeatability matters, and use closures with mutation only when remembering state is an explicit part of the abstraction.
fun counter(start:Int):()->Int {var n=start; return { n+=1; n }}
fun main(){val a=counter(0);val b=counter(10);println(a());println(a());println(b())}1 2 11
Calls through a share one captured variable; b captures a separate variable created by another factory call.
Try it yourself
Write a predicate-accepting count function and use it for both even values and positive values.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING