January 2018
Intermediate to advanced
434 pages
14h 1m
English
Another way of initializing properties is with the lazy modifier; lazy() is basically a function that takes a lambda and returns an instance of lazy, which serves as a delegate for implementing a lazy property. Let's take a look at the next example:
public class Student{ val name: String by lazy { “Aanand Shekhar Roy” }}
By lazy initialization, we postpone initialization until we first use it. The property is initialized only when we first access it, and the same value is returned for subsequent accesses. That's why it is mandatory to mark the variable immutable. This can really help us with initialization of heavy objects, which takes a lot of time. Initializing them lazily can improve our startup time. The only con is that ...
Read now
Unlock full access