What is Lateinit in Kotlin and when would you use it?

Technology CommunityCategory: KotlinWhat is Lateinit in Kotlin and when would you use it?
VietMX Staff asked 3 years ago

lateinit means late initialization. If you do not want to initialize a variable in the constructor instead you want to initialize it later on and if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. It will not allocate memory until 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"
}

There are a handful of use cases where this is extremely helpful, for example:

  • 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 (eg. @Autowired).