Lateinit vs Lazy in Kotlin
I am Naimish Trivedi, I have a far experience in native and hybrid programming. I have presented the programming concept here in a simple and easy way from my experience. This will be very useful for native Developers.
In this Article, we will learn about the lateinit vs lazy properties in Kotlin.
In Kotlin for Android development, lateinit and lazy are both mechanisms used to delay the initialization of properties. However, they serve different purposes and have different use cases.
lateinit
lateinit is a modifier that is used for non-null properties. It allows you to declare a property without initializing it immediately, but you must initialize it before using it, otherwise, it will throw a LateInitializationException.
for example :
In this example, message is declared with lateinit, but it must be initialized before calling printMessage().
lazy
lazy is a function that takes a lambda and returns an instance of Lazy<T>, which has a value that will be computed only upon the first access. It is useful when the initialization of a property is computationally expensive or you want to defer its initialization until it's actually needed.
for example :
In this example, studentModel will be initialized upon the first access to it via printProperty(). The lambda provided to lazy will be executed only once.
Differences
In summary, use lateinit when you have a non-nullable property that must be initialized before use, and use lazy when you want lazy initialization for properties, especially when the initialization is expensive or can be deferred.
That's it for now.
Thanks
Happy Coding..!!
QA | Manual tester | Game tester | Software tester
11 个月Thanks for sharing
Company Owner
11 个月Love this
--
11 个月Beautifully said! This article succinctly captures the essence of the difference between lateinit and lazy in Kotlin for Android development.
Student at GTUPGSCHOOL
11 个月Thanks for posting
Jr.Android Developer
11 个月Thanks for sharing helpful Article ??