Home > other >  What is the application of "by lazy" in Android-Kotlin?
What is the application of "by lazy" in Android-Kotlin?

Time:09-27

In which places should the by lazy be used?

Why should it be used?

How does it make the code better

for example:

val currentResult: MutableLiveData<String> by lazy {
          MutableLiveData<String>()
}

CodePudding user response:

In which places should the by lazy be used?

They should be used where you don't need unnecessary initialization of the variables. These are val properties, so after initialization, that same object would be used in the whole run of the class.

Why should it be used?

lazy should be used when any of your objects are heavy and they take a long time to initialize. Here lazy properties can help to skip that delay which could be caused by the initialization of those objects. As lazy would only initialize the variable when it is called, otherwise it won't be created.

How does it make the code better

By lazily loading heavy objects, it increases the performance of the code, as any delay in the loading, which could've been caused due to the initialization of these heavy variables is now eliminated. It keeps the memory free, as these won't be initialized until the moment, they are called by the code.

  • Related