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.
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.
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.
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.
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
Related Articles
- Kotlin Ternary Conditional Operator
- How to parse JSON in Kotlin?
- Check if a “lateinit” variable is initialized in Kotlin?
- Format String in Kotlin With Examples