Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - lateinit VS Any? = null

Tags:

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?

like image 627
fergdev Avatar asked Feb 29 '16 02:02

fergdev


People also ask

When should I use Lateinit?

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.

What is the Lateinit modifier for?

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.

What's the difference between lazy and Lateinit?

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.

What is Lateinit VAR in Kotlin?

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.


1 Answers

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.

like image 177
dishan Avatar answered Sep 30 '22 19:09

dishan