Lateinit in Kotlin
Lateinit in Kotlin is a keyword or a reserved word. A keyword is a token reserved by a language that has a specific meaning in a language and cannot be used as a name for an identifier.
The lateinit in Kotlin is used for the late initialization of a variable in Kotlin. Using the lateinit keyword, you can declare a variable and not provide an initial value for the variable. It specifies that the variable will be initialized later in the program.
The syntax for using the lateinit keyword is as follows.
lateinit var variableName: String
Let us now understand the use of lateinit with an example.
fun main() {
//variable declaration
lateinit var myString: String
println("It is the middle of the program.")
//Variable initialization
myString = "Coding Ninjas is your platform to Learn and Grow!"
println(myString)
println("It is the end of the program.")
}
Output
It is the middle of the program.
Coding Ninjas is your platform to Learn and Grow!
It is the end of the program.
When you try to print the variable declared using lateinit and print it without initializing, it will throw an error. Let's see this with an example.
fun main() {
//variable declaration
lateinit var myString: String
println(myString)
}
Output

An exception is raised when we declare the variable using lateinit and print it without initializing.
You can also change the content of the variable. You can change the variable value simply as you do for normal variables. Following is an example.
fun main() {
//variable declaration
lateinit var myString: String
myString = "Coding Ninjas is a great platform to Learn and Grow!"
println(myString)
myString = "Coding Ninjas is an excellent platform to practice coding problems."
println(myString)
}
Output
Coding Ninjas is a great platform to Learn and Grow!
Coding Ninjas is an excellent platform to practice coding problems.
How to check if the lateinit variable is initialized?
Kotlin also provides a method to check whether the variable declared using lateinit is initialized. You can check for lateinit variables within the program. In this way, you can avoid the error from occurring.
The method name is isInitialized, and the syntax to use this method is as follows.
this::variableName.isInitialized
If you are invoking the method from an inner class, you have to mention the class name. In this case, the syntax changes to the following.
this@parentClassName::variableName.isInitialized
The isInitialized method returns true if the variable is initialized and returns false otherwise.
Let us now see an example to understand the usage of this method.
class Ninja {
lateinit var myString: String
fun check() {
//checking whether the variable is initialized or not.
println(this::myString.isInitialized)
//Initializing the variable.
myString = "Coding Ninjas is the way to go!"
//checking whether the variable is initialized or not.
println(this::myString.isInitialized)
}
}
//Main Function
fun main(){
Ninja().check()
}
Output
false
true
Let us now discuss the usage of the lateinit keyword in Kotlin.
Usage of Lateinit in Kotlin
You can see that there are two main uses of lateinit in Kotlin. They are as follows.
-
Late Initialization of variable.
If you are sure that a variable will be initialized in the later program, then you can declare the variable using the lateinit keyword. It specifies that the variable will be initialized later in the program.
-
Injecting an object using Dagger
Dagger is a compile-time dependency injection framework in Kotlin. Dependency injection helps separate the object creation from the objects that are created. It helps in making the code clean and understandable.
Benefits of Lateinit
The benefits of using lateinit in Kotlin include:
-
Improved Readability: lateinit allows for cleaner code by avoiding nullable types or optional initialization, making the code easier to read and understand.
-
Performance: By using lateinit, we avoid unnecessary null checks and assignments, leading to better runtime performance compared to nullable types.
-
Avoidance of Nullability: lateinit allows us to work with non-nullable types, ensuring that the property will be initialized before accessing it, reducing the risk of null pointer exceptions.
-
Flexibility: lateinit provides flexibility in initializing properties, allowing for initialization at a later stage in the program's execution, which can be beneficial in certain scenarios, such as dependency injection or Android development.
-
Compatibility: lateinit is fully interoperable with Java code, allowing Kotlin classes with lateinit properties to be used seamlessly with existing Java codebases.
Now, let's move to the last section of this article. We will see how the lateinit in Kotlin differs from the lazy keyword.
How is lateinit in Kotlin different from lazy keyword?
Before understanding the difference between lazy and lateinit in Kotlin, let us first understand the lazy keyword.
The lazy keyword is used where you have classes whose object creation is slow. Some classes may have many variables and methods, so it takes time to create an object of this class. Now suppose you want to use this object in some other class. In this case, there may be cases where you do not need the object, but the creation still takes some time.
In such situations, you can use the lazy keyword to specify that the object will only be created when it is called. This way, you can save time in creating an object that may never be used. The creation of such objects may have caused delays if not used the lazy keyword.
Example of lazy keyword
//Heavy Class.
class A{
private val variableName : String = "Hello Ninja!"
//Some more heavy variables and methods that take time.
}
//Other Class
class B {
//using the lazy keyword.
private val objectOfA: A by lazy {
println("Object Creation")
A()
}
fun returnObject() {
println("Object of A : " + objectOfA)
}
}
//Driver Function
fun main() {
var ObjectOfB = B()
println("Initialized the object of class B.")
println("The gap between the actual use of the object of class A.")
//Use of object of class A.
ObjectOfB.returnObject()
}
Output
Initialized the object of class B.
The gap between the actual use of the object of class A.
Object Creation
Object of A : A@2b71fc7e
Note: The object is not initialized each time it is used. It is only initialized the first time.
Both the lateinit and the lazy keywords are used for property initialization in Kotlin, but it is necessary to understand when to use which keyword. The main difference between the lateinit and the lazy keywords is as follows.
-
The lateinit keyword is used for the late initialization of the object. The object is created in the memory, but the value is not assigned. The value is assigned later in the program.
Whereas with the lazy keyword, the object is not created unless used. In the lazy keyword, an object may never be created if we do not use/call the object.
- The lazy keyword is used to save the run time of your program by avoiding the creation of heavy objects which are not used in the program. Whereas lateinit only delays the initialization of the object.
Must Read Elvis Operator Kotlin
Frequently Asked Questions
How many programming languages are there?
Codes/Programs are written in a programming language. There are not a single but hundreds of programming languages. Each language has something different and advantageous.
What does the lazy keyword do in Kotlin?
The lazy keyword is used to specify that the object is only created when used. It is used when you create an object of a heavy class within another class and may not use the object. In such cases, the lazy keyword helps in saving a lot of time.
What method is used to check whether a lateinit variable is initialized?
The method isInitialized is used to check whether the lateinit variable is initialized or not. It returns true if the object is initialized and false otherwise.
Why not use Lateinit in Kotlin?
Using lateinit may lead to runtime errors if the property is not initialized before accessing it, resulting in potential crashes.
What is the difference between null and Lateinit in Kotlin?
Null represents an absence of a value, while lateinit is used for non-nullable properties that are initialized later in the program.
What are keywords in Kotlin?
The keywords in Kotlin are reserved tokens with a particular meaning and cannot be used as a name for an identifier. Examples of such keywords include as, object, class, fun, etc.
Conclusion
This article discussed the keyword lateinit in Kotlin. We also discussed the method to check whether a lateinit variable is initialized. We also talked about the lazy keyword and how it differs from the lateinit in Kotlin.
To check out the most common interview questions on Kotlin, you can check out Top 30 Kotlin Interview Questions - Coding Ninjas Coding Ninjas Studio.
I hope you would have gained a better understanding of these topics now! Are you planning to ace the interviews with reputed product-based companies like Amazon, Google, Microsoft, and more?
Attempt our Online Mock Test Series on Coding Ninjas Studio now!
Happy Coding!