Working with the Lazy delegate
Lazy initialization is another design pattern that has its dedicated delegate implementation included in the standard library. The concept of lazy initialization refers to the strategy of delaying the creation of an object, calculation of a value, or execution of some expensive operation until the first time it's needed. In this recipe, we are going to define a sample class, CoffeeMaker
, and declare an object of its type via the Lazy delegate. Then we are going to perform example operations on the object to explore how the lazy delegate is working in action.
How to do it...
- Let's start with defining the
CoffeeMaker
class:
class CoffeeMaker { init { println("I'm being created right now... Ready to make some coffee!") } fun makeEspresso() { println("Un espresso, per favore!") } fun makeAmericano() { print("Un caffè americano, per favore!") } }
- Declare a variable of the
CoffeMaker
type using thelazy
delegate:
val coffeeMaker: CoffeeMaker by...