1. Introduction
In this short article, we are going to present how to find out that lateinit variable in Kotlin has been initialized.
2. Late-initialized variable
The non-null variables usually must be initialized in the constructor and this is the normal behavior in many programming languages, Kotlin is not an exception in this case. However, that approach is not so obvious in cases when variables are initialized through the dependency injection or other configuration methods. In such situations, we cannot add variable initializer in the constructor but still want to avoid constantly checking if variables are null in the class body.
To handle such cases Kotlin introduced the lateinit modifier:
In this example, the lateinitTest
is marked with lateinit modifier. This adds some extra features to this variable.
3. Checking if the lateinit variable is initialized
We can check whether a lateinit variable has been initialized using the .isInitialized
property:
In this example before initializing the variable: lateinitTest = LateinitTest()
the println(this::lateinitTest.isInitialized)
command will display false
. After lateinitTest
variable has been initialized .isInitialized
property will be presenting true
. Note that using lateinit
variable before initialization will results in UninitializedPropertyAccessException.
The output will be:
Note that lateinit
modifier could be used only on non-primitive types and on property that does not have a custom getter or setter.
When we try to access a lateinit property before it has been initialized the special exception will be thrown with all information about what went wrong.
This will produce the following exception:
4. Conclusion
In this short tutorial, we present a way to check if the lateinit variable has been initialized. Kotlin luckily provides a dedicated property that does this job well.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}