9 Working with laziness
- Understanding the importance of laziness
- Implementing laziness in Kotlin
- Composing with laziness
- Creating a lazy list data structure
- Handling infinite streams
Imagine you’re the bartender in a tiny bar that offers two products: espresso and orange juice. A customer enters and sits. You have two options:
- You prepare an espresso, press an orange juice, bring the two to the customer, and let them choose.
- You ask the customer what they’d like to have, prepare it, and serve it.
In programming terms, in the second case, you’re being lazy, whereas in the first case, you’re being strict. Choosing the best strategy is up to you. This chapter isn’t about morals, but about efficiency.
In this case, there are other options. You could eagerly prepare an espresso and an orange juice before any customer enters. Once a customer comes in, ask the person to pick what they want, serve what’s requested, and immediately make a beverage in preparation for the next customer. Seems crazy? Not so.
Imagine you’re also offering apple pies and strawberry pies. Would you wait for a customer to enter and choose one kind of pie to prepare it? Or would you eagerly prepare one of each kind? If you choose to be lazy, you would wait for the customer to choose, let’s say apple pie. Then you’d prepare an apple pie, cut a slice, and bring it to the customer. This would be the lazy approach, although you’d have at the same time prepared the other apple pie slices.