Search code examples
androidkotlinkotlin-null-safety

Kotlin - lateinit VS Any? = null


In Kotlin there appears to be two method of declaring a variable inside an object that can be null and instantiated after the object is created.

var myObject : Any? = null

or

var lateinit myObject : Any  

I am confused about why the lateinit keyword is needed if we can just make the var nullable and assign it later. What are the pros and cons of each method and in what situation should each one be used?


Solution

  • Here is how I see the difference according to my current knowledge in Kotlin.

    First one:

    var myObject1 : Any? = null
    

    Here myObject1 is a property that is nullable. That means you can assign null to it.

    Second one:

    lateinit var myObject2 : Any
    

    Here myObject2 is a non-null property. That means you cannot assign null to it. Usually if a property is non-null you have to initialize it at the declaration. But adding the keyword lateinit allows you to postpone the initialization. If you try to access the lateinit property before initializing it then you get an exception.

    In short the main difference is that myObject1 is a nullable and myObject2 is a non-null. The keyword lateinit provide you a convenience mechanism to allow a non-null property to be initialize at a later time rather than initializing it at the declaration.

    For more info check this.