DEV Community

Pulkit
Pulkit

Posted on

How to use lazy in Kotlin

We all have been there. Kotlin is good, and we want to declare a variable outside of onCreate() so that we can access the member variable anytime outside of it too. Now to make it non null, you have to either send some data and init the variable in the constructor. Which is not possible in most cases.

For performance reasons
Now don't just use lazy just like this:-

private val someString by lazy {
"someData"
}

but do like this :-

private val someString by lazy(LazyThreadSafetyMode.NONE) {
"someData"
}

https://www.youtube.com/watch?v=mNviUg0ocsk

Top comments (0)