The lazy property

The lazy is a very handy feature in Kotlin. We don't initialize any object unless we require it. This is quite an optimized approach. A typical case can be binding on a view with an object when required. We initialized a toolbar in HomeActivity to demonstrate the lazy property. There can be many other use cases using it:

    val toolbar by lazy { find<Toolbar>(R.id.toolbar) }

A lazy delegated property can only be used with val.  Whatever you define inside the block that will get executed only once.

Use it carefully, initializing a heavy object when it is required can affect application response. Do not execute functions doing too much inside the lazy block.

Get Kotlin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.