Lateinit keyword

There are many cases when you need to create a variable but you don't want to initialize it at the time of declaration/creation of the variable because you are sure that the variable will be initialized before its access/usage.

One way of achieving this is by making the variable nullable like this:

var courseId: String? = null

But what if you don't want to make it nullable? Here comes the use of the lateinit keyword.

The lateinit keyword is used for the late initialization of variables.

lateinit var courseName : String  
fun doSomething() {  
    courseName = "bolt uix"  

You should be very sure that your lateinit variable will be initialized before accessing it otherwise you will get:

UninitializedPropertyAccessException: lateinit property courseName has not been initialized

If you are not sure about the nullability of your lateinit variable then you can add a check to check if the lateinit variable has been initialized or not by using isInitialized:

if(this::courseName.isInitialized) {
// access courseName
} else {
// some default value

NOTE: To use a lateinit variable, your variable should use var and NOT val. Lateinit is allowed for non-primitive data types only and the variable can't be of null type. Also, lateinit variable can be declared either inside the class or it can be a top-level property.

Usage of lateinit

  • For late initialization of variables.
  • For injecting an object using Dagger.

Add linl : playground