Skip to content

What is ‘lateinit’ Variable in Kotlin? Naveen (NNK) Spark By {Examples}

  • by

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.

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.

// Syntax
lateinit var variableName: DataType

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.

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
}

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.

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

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.

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.

Conclusion

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

 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  Read More Kotlin 

Leave a Reply

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