1. Overview

In Kotlin, there are a few different approaches to lazy-initialize or even late-initialize variables and properties.

In this quick tutorial, we’re going to learn to check the initialization status of a lateinit variable.

2. Late Initialization

Using lateinit variables, we can defer a variable’s initialization. This is especially useful while working with dependency injection or testing frameworks.

Despite being useful, there is one big caveat while using them: if we access an uninitialized lateinit variable, Kotlin throws an exception:

private lateinit var answer: String

@Test(expected = UninitializedPropertyAccessException::class)
fun givenLateInit_WhenNotInitialized_ShouldThrowAnException() {
    answer.length
}

The UninitializedPropertyAccessException exception signals the fact that the underlying variable is not initialized yet.

In order to check the initialization status, we can use the isInitialized method on the property reference:

assertFalse { this::answer.isInitialized }

Here, with the :: syntax, we get a reference to the property. This obviously returns true when we assign something to the variable:

answer = "42"
assertTrue { this::answer.isInitialized }

Please note that this feature is only available on Kotlin 1.2 or newer versions.

3. Conclusion

In this tutorial, we saw how to check the initialization status of a lateinit variable.

As usual, the sample codes are available over on GitHub.

guest
0 Comments
Inline Feedbacks
View all comments