Differences between lateinit and lazy

Florence
2 min readJul 14, 2022

--

Properties in Kotlin are declared using var or val keywords. Late init and lazy are both used to initialise the properties that will be used in the future.
Since both keywords are used to declare properties that will be used later in time, let’s take a look at them and their differences.

Late Init
In the following example we have a variable myClass, the variable is first initialised using lateinit then it is given a value later on.Using isInitialized method we are able to tell if the variable is initialised or not.

When we run the code block, the output will look like this:

We can see in the first print line, the variable though it has been declared, it has not been initialised therefore it returns a false. After assigning the variable a value it returns true.

Lazy

The lazy keyword initialises an object and the object will only be created when it is accessed.

In the following example we will initialise myPoem variable lazily. We can see that the variable is only created when it is called, and the second time it is called it uses the same reference as before.

When we run the code block, the output will look like this:

Differences between lateinit and lazy:

  1. A lateinit property can not be nullable but a lazy property can be nullable.

2. Lateinit is used to declare mutable variables i.e. uses the keyword var while lazy is used to declare immutable variables by using the keyword val.

3. Late init can not be used to declare primitive data types such as Int whereas lazy can be used to declare primitive data types.

4. Lazy initialisation is thread safe whereas lateinit doesn’t define thread safety.

Thats all for today, happy coding!

--

--