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?
lateinit means that variable must be initialised later. It should be initialized before accessing it. If you attempt accessing uninitialized lateinit variable UninitializedPropertyAccessException will be thrown. It's always better to avoid using nulls in your app.
The lateinit keyword stands for “late initialization.” When used with a class property, the lateinit modifier keeps the property from being initialized at the time of its class' object construction.
lateinit can only be used with a var property whereas lazy will always be used with val property. A lateinit property can be reinitialised again and again as per the use whereas the lazy property can only be initialised once.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With