• Post author:
  • Post category:Kotlin
  • Post last modified:May 9, 2024
  • Reading time:6 mins read

In Kotlin, you can declare a property or variable as 'lateinit' (short for “late initialization”) when you want to initialize a non-null value before you try to access it. This is particularly useful when working with dependency injection or when you’re certain that the variable will have a value set before it’s used, but you can’t initialize it immediately.

Advertisements

Related: How to check if ‘lateinit’ variable is initialized

1. Usage of lateinit Variable

In Kotlin, lateinit variables are used when you know that a property will be initialized before it is accessed, but you can’t initialize it immediately, For example:

  • When working with dependency injection
  • Certain Android app development scenarios.
  • Testing
  • Lazy initialization

lateinit allows you to defer the initialization until later in your code while ensuring that you won’t encounter null pointer exceptions when accessing the variable.

1.1 Syntax of lateinit Variable

Following is the syntax to declare lateinit variable.

[kotlin theme=”darcula” runnable=”false”] // Syntax lateinit var variableName: DataType [/kotlin]

Note that ‘lateinit‘ modifier is allowed only on mutable local variables like var. Hence, you cannot use for val variables.

1.2 Using lateinit Variable

Let’s create and use the lateinit variable in a simple example.

[kotlin theme=”darcula”] fun main() { // Declare lateinit variable lateinit var name: String lateinit var city: String // Initialize lateinit variable name = “Kumar” // print println(name) // Output: Kumar println(city) // Output: Error } [/kotlin]

In this example, we simply created two lateinit variables name and city, later only name variable has been initialized with a non-null value Kumar. When we print name variable, it prints the associated value Kumar on the console. Printing city variable returns an exception UninitializedPropertyAccessException as it’s not initialized.

2. Handling Exception

So when you access lateinit variable without initializing, Kotlin returns an exception UninitializedPropertyAccessException with error message “lateinit property has not been initialized“. By using tr-catch you can handle this exception and take appropriate action.

[kotlin theme=”darcula”] fun main() { // Declare lateinit variable lateinit var name: String lateinit var city: String // Initialize lateinit variable name = “Kumar” // print println(name) // Output: Kumar try{ println(city) // Output: Error } catch (e: UninitializedPropertyAccessException) { println(“Catch exception and take appropriate action”) } } [/kotlin]

Check lateinit Variable is Initialized

To check if a lateinit variable has been initialized in Kotlin, you can use the ::variableName.isInitialized syntax. This expression will return true if the lateinit variable initialized a non-null value, and false if it is not initialized.

The :: creates a member reference or a class reference.

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

Alternatively, you can also use this::name.isInitialized

Conclusion

In this article, you have learned what is lateinit variable in Kotlin and how to declare, initialize a value, and access the variable. In summary