Skip to content

Check if a “lateinit” variable is initialized in Kotlin? Asif Spark By {Examples}

  • by

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 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.

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.

Syntax of isInitialized

// Snntax
::variablename.isInitialized

Example of using isInitialized

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
}

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.

Remember 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.

In this article, we will see how to avoid the error by using the variable after checking it’s been initialized. 

Using UninitializedPropertyAccessException to check lateinit Variable Initialized

Most modern programming languages including Kotlin have the 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.

Syntax:

// Syntax of using exception UninitializedPropertyAccessException
try{
// Do something.
}
catch(e: UninitializedPropertyAccessException){
// Do something
}

Example:

// 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.”)
}
}

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.

Using Function Definition

In the above part 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 to know whether we initialized any variable. 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. 

Example code:

// 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.”)
}
}

Yields below output.

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.

In Kotlin 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.

Example code:

// 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.”)
}
}

Yields below output.

In the above code, we have created a class called “MyClass”. Next, we have 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 so that we could know whether we had successfully initialized the variable.

Conclusion

In this article, you learned how to check if we initialized the “latent” variable in Kotlin. We mainly used the isInitialized propery, UninitializedPropertyAccessException exception class. We also adopted several methods like using functions, classes etc. to see different variations of the same problem. 

More Resources:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/format.htm
 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 lateinit (short for “late initialization”) when you want to  Read More Kotlin 

Leave a Reply

Your email address will not be published. Required fields are marked *