Google News
logo
Kotlin - Interview Questions
What is Lateinit in Kotlin, and when is it used?
Lateinit means late initialization. It is used when you do not want to initialize a variable in the constructor and instead initialize it later.

You should declare that variable with lateinit keyword to guarantee the initialization, not before using it. It will not allocate memory until it is initialized. You cannot use lateinit for primitive type properties like Int, Long, etc.
lateinit var test: String  
fun doSomething() {  
    test = "Some value"  
    println("Length of string is "+test.length)  
    test = "change value"  
}  ​
This is mainly used in the following cases :

Android : variables that get initialized in lifecycle methods.

Using Dagger for DI : injected class variables are initialized outside and independently from the constructor.

Setup for unit tests : test environment variables are initialized in a @Before - annotated method.

Spring Boot annotations (e.g., @Autowired).
Advertisement