Folding Events
What have we learned after all this folding? Using recursion allowed us to avoid keeping a mutable temporary state and instead keep everything immutable and pure, relying upon the Kotlin stack. What about when it’s not possible to keep the state change inside a single computation?
Let’s imagine we need to model an entity with different states, like a finite state machine,[30] and that these states also change the behavior of the entity itself. To visualize this, let’s consider how we would model a door. It has two states: open and closed. It also has two very different behaviors when it’s open versus when it’s closed, as anyone who’s smacked into a glass door can tell you.
To make the example more interesting, we’ll also consider ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access