9 Working with laziness

 

In this chapter

    • 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:

    1. You prepare an espresso, press an orange juice, bring the two to the customer, and let them choose.
    2. 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.

    9.7 Strictness versus laziness

    9.8 Kotlin and strictness

    9.9 Kotlin and laziness

    Laziness implementations

    9.10.1 Composing lazy values

    9.10.2 Lifting functions

    9.10.3 Mapping and flatMapping Lazy

    9.10.4 Composing Lazy with List

    9.10.5 Dealing with exceptions

    Further lazy compositions

    9.11.1 Lazily applying effects

    9.11.2 Things you can’t do without laziness

    9.11.3 Creating a lazy list data structure

    Handling streams

    9.12.1 Folding streams

    9.12.2 Tracing evaluation and function application

    9.12.3 Applying streams to concrete problems

    Summary