How to check if a lateinit
variable has been initialized in Kotlin? You can check if a lateinit
variable is initialized by using ::variable.isInitialized
. This returns true when the lateinit variable is initialized, if not it returns false.
In Kotlin, you can declare a variable/property as a lateinit (short for “late initialization”) when you want to initialize a non-null
value before you try to access it. Programmers use this lateinit
variable only when they are sure that they will use the variable somewhere before the initialization.
If you try to use a variable before initializing then Kotlin will raise an exception UninitializedPropertyAccessException
with the error message “lateinit property has not been initialized“. Hence, it is always best practice to check if the lateinit
variable is initialized.
In this article, you will learn how to check if a lateinit
variable is initialized in Kotlin and how to handle it when not initialized with examples.
1. Check lateinit Variable is Initialized in Kotlin
To check if a lateinit
variable has been initialized use ::variable.isInitialized
property in Kotlin. isInitialized
returns true when the lateinit variable has been initialized with a non-null value, when not initialized, it returns false.
1.1 Syntax of isInitialized
Following is the syntax of the isInitialized
.
1.2 Example of using isInitialized
[kotlin theme=”darcula”] class Example { // Delare lateinit variable lateinit var name: String fun initializeName() { // Initialize lateinit variable name = “Kumar” } fun printName() { // Check if lateinit variable is initialized if (::name.isInitialized) { println(name) } else { println(“lateinit varialbe ‘name’ is not initialized”) } } } // Kotlin main() method fun main() { val example = Example() // Access before intialize example.printName() // Output: lateinit varialbe ‘name’ is not initialized // Access after intialize example.initializeName() example.printName() // Output: Kumar } [/kotlin]In this example, the name
variable is declared as a lateinit property of type String. This variable has been initialized in the initializeName()
function. The ::name.isInitialized
check is used to determine if the name property has been initialized to avoid a lateinit property access exception.
1.2 Checking from Inner class
If you are using a listener or inner class, use the following syntax
[kotlin theme=”darcula” runnable=”false”] // Using with inner class this@OuterClassName::variableName.isInitialized [/kotlin]1.4 Checking from Another Class
If you have a lateinit
property in one class and need to check if it is initialized from another class, First, create a function to check if the property is initialized and call that function from any other class. Below is a snippet.
Note that using lateinit should be done with caution as if you attempt to access the property before it’s initialized, it will result in an UninitializedPropertyAccessException
. Let’s see with an example.
2. Handling UninitializedPropertyAccessException
Most modern programming languages including Kotlin have exception handling which helps properly handle the errors. The UninitializedPropertyAccessException
is a part of the Exception class in Kotlin which is raised when you refer lateinit
without initializing. So we can utilize this in Kotlin to check whether we initialized the variable.
2.1 Syntax:
[kotlin theme=”darcula” runnable=”false”] // Syntax of using exception UninitializedPropertyAccessException try{ // Do something. } catch(e: UninitializedPropertyAccessException){ // Do something } [/kotlin]2.2 Example:
[kotlin theme=”darcula”] // Define the main function which is our driver function. fun main() { lateinit var myVariable: String // To avoid any error wrap the code in try catch block. try { myVariable.length // Access the lateinit variable println(“myVariable has been initialized.”) } catch (e: UninitializedPropertyAccessException) { // Print the following exception println(“myVariable has not been initialized.”) } // Initialize myVariable myVariable = “Initialized value” // To avoid any error wrap the code in try catch block. try { myVariable.length // Access the lateinit variable println(“myVariable has been initialized.”) } catch (e: UninitializedPropertyAccessException) { println(“myVariable has not been initialized.”) } } [/kotlin]In the above code, we have declared a lateinit
variable named myVariable
with a string data type. Next, we used this variable within try-catch. If someone initialized it, it would have some length. However, since we have not initialized, it doesn’t have a length property, so myVariable.length
raises the exception UninitializedPropertyAccessException
and prints "myVariable has not been initialized."
Next, we initialized the variable to the value “Initialized value” hence, it prints "myVariable has been initialized"
.
Yields below output.
3. Using Function Definition
In the above section, we learned about how to determine whether we initialized a variable using the UninitializedPropertyAccessException class exception. However, the problem associated with the above code is that we are writing the same piece of code blocks again and again. Also, we may encounter situations where we may variable in a different class or function. Hence to avoid this inconvenience we can adopt the functions.
3.1 Example code:
[kotlin theme=”darcula”] // Define a custom class and initialize the variable class MyClass { lateinit var myVariable: String } // Define a function which takes the custom variable fun isInitialized(variable: MyClass): Boolean { // Put your code in a try catch block to avoid error. return try { variable.myVariable true } catch (e: UninitializedPropertyAccessException) { false } } // Our driver code. fun main() { // Create an object. val myClass = MyClass() // Check if the variable is initialized if (isInitialized(myClass)) { println(“myVariable has been initialized.”) } else { println(“myVariable has not been initialized.”) } // Initialize myVariable myClass.myVariable = “Initialized value” if (isInitialized(myClass)) { println(“myVariable has been initialized.”) } else { println(“myVariable has not been initialized.”) } } [/kotlin]Yields below output.
4. Using Custom Class Method
In Kotlin, because we often work with different classes and objects, it’s really important for us to know if we have initialized a variable with a value. This helps us avoid errors.
We can use the “this
” keyword to access the variable within the class. If it returned true then it means that we already initialized the variable otherwise it means we have not initialized the variable yet.
4.1 Example code:
[kotlin theme=”darcula”] // Define the class class MyClass { // Initialize the variable here. lateinit var myVariable: String // Create a function to check if the variable has been initialized. fun isMyVariableInitialized(): Boolean { // Wrap the code in a try catch block. return try { this.myVariable true } catch (e: UninitializedPropertyAccessException) { false } } } fun main() { // Create an object val myClass = MyClass() // If else statement to check if the variable has been initialized. if (myClass.isMyVariableInitialized()) { println("myVariable has been initialized.") } else { println("myVariable has not been initialized.") } // Initialize myVariable myClass.myVariable = "Initialized value" // If else statement to check if the variable has been initialized. if (myClass.isMyVariableInitialized()) { println("myVariable has been initialized.") } else { println("myVariable has not been initialized.") } } [/kotlin]Yields below output.
In the above code, we have created a class called “MyClass
” and declared a variable named ‘myVariable
’. We created a function under the class named “isMyVariableInitialized
” which checks if the variable “myVariableexists
“. Under the main function, we created an object and called the function “isMyVariableInitialized
() ” twice to check if the variable is initialized. First, we called it without initializing the variable and next, we initialized the variable and called the function again.
5. Conclusion
In this article, you learned how to check if we initialized the “lateinit
” variable in Kotlin. We mainly used the isInitialized
property, UninitializedPropertyAccessException
exception class. We also adopted several methods like using functions, classes etc. to see different variations of the same problem.
Related Articles
- Kotlin Ternary Conditional Operator
- How to parse JSON in Kotlin?
- What is ‘lateinit’ Variable in Kotlin?
- Format String in Kotlin With Examples