DEV Community

Pulkit
Pulkit

Posted on

2 1

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)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay