1. Introduction
In this article, we will focus on UninitializedPropertyAccessException in Kotlin. We will present when this exception happens and how to deal with it.
2. Code example
Let's start with a simple Kotlin program that throws UninitializedPropertyAccessException
on runtime:
We have class A
with a lateinit
field list and class B
that creates an instance of class A
and trying to access list
.
You will not get a compilation error here, but in runtime, the exception will be thrown:
This exception is thrown because we try to access not initialized property list
from the class A
. We don't face a compilation error here because the list
variable was marked with lateinit
statement.
How to deal with such errors? The answer is of course obvious we need to create an instance of list
before trying to add elements to this list, a good practice is also checking if lateinit variable is initialized.
3. The solution
The solution is simple, we need to initialize the list
property before using this variable:
In this example, we also used isInitialized
property that is used to check if a lateinit
variable has been initialized.
3. Conclusion
In this short article, we presented how to deal with UninitializedPropertyAccessException
in Kotlin. This exception is related to lateinit
variables that have not been initialized before using them in any kind of way.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}