How to deal with UninitializedPropertyAccessException in Kotlin?

June 06, 2021 No comments Kotlin UninitializedPropertyAccessException

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:

class A {
    lateinit var list: MutableList<String>
}

class B {
    val a = A();

    fun print() {
        a.list.add("test")
    }
}

fun main() {
    val b = B();
    b.print();
}

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:

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property list has not been initialized
    at A.getList(Lateinit.kt:2)
    at B.print(Lateinit.kt:9)
    at LateinitKt.main(Lateinit.kt:15)
    at LateinitKt.main(Lateinit.kt)

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:

import java.util.*

class A {
    lateinit var list: MutableList<String>;

    fun addElement(element: String) {
        if (!::list.isInitialized) {
          list = LinkedList<String>();
        }

        list.add(element);
    }
}

class B {
    val a = A();

    fun print() {
        a.addElement("test");

        print(a.list);
    }
}

fun main() {
    val b = B();
    b.print(); // [test]
}

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.

{{ message }}

{{ 'Comments are closed.' | trans }}