Home Effectively using Lazy
Post
Cancel

Effectively using Lazy

Effectively using property delegation function lazy in kotlin.

Using lazy in kotlin

We all know kotlin’s standard delegation function lazy which lazily initialises our object, let’s say you have condition if this object is initialised you need to either dispose the resources.

Now normally we would do the following

  val resource<T> by lazy<T> {
    //lazy initialisation logic
  }

and when we need to dispose resource we would do

  resource.dispose()

Catch

But there is catch this would internally run the lazy initialisation logic and then dispose the resource, we are unnecessarily initialising and then disposing.

Instead we can use a public method that lazy interface provides, by this we are effectively using the lazy property delegation.

  val  resourceDelegate = lazy { /** resource initialising **/}
  val resource:ResourceType by resourceDelegate
  if(resourceDelegate.isInitialized()){
     resource.dispose()  
  }

More reading:

Lazy interface doc. How lazy-initialization work

This post is licensed under CC BY 4.0 by the author.