Kotlin - ‘lateinit’ Keyword and lazy Initialization

SHISHIR
PROGRAMMING LITE
Published in
2 min readApr 24, 2020

‘lateinit’ Keyword

In Kotlin, when we declare a variable we have to initialize it with a value or we need to assign null. But if we don’t want to initialize the variable with null or any value. Rather we want to initialize it in future with a valid value, then we have to use lateinit. Actually it is a promise to compiler that the value will be initialized in future. But remember:

  • Use it with mutable variable[var]
lateinit var name: String   //Allowed 
lateinit val name: String //Not Allowed
  • Allowed with only non-nullable data types
lateinit var name: String       //Allowed 
lateinit var name: String? //Not Allowed
  • lateinit values must be initialized before we use it.

NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.

lazy initialization

  • lazy is lazy initialization.
  • Lazy initialization was designed to prevent unnecessary initialization of objects.
  • Your variable will not be initialized unless you use it.
  • It is initialized only once. Next time when you use it, you get the value from cache memory.
  • It is thread safe(It is initializes in the thread where it is used for the first time. Other threads use the same value stored in the cache).
  • The variable can only be val.
  • The variable can only be non-nullable.
  • lazy() is a function that takes a lambda and returns an instance of lazy.
public class Example{
val PI: Float by lazy { 3.1416 }
}
  • While using Singleton Pattern (Object Declaration in Kotlin) we should use lazy, as it will be initialized upon first use.
  • lazy may also be very useful when implementing read-only(val) properties that perform lazy-initialization in Kotlin.

--

--

SHISHIR
PROGRAMMING LITE

{ 'designation' : 'Lead Software Engineer' , 'hobby' : [ 'Music', 'Photography', 'Travelling' ] ,’email’: ‘shishirthedev@gmail.com’ }