Sling Academy
Home/Kotlin/How to Initialize Late Variables in Kotlin

How to Initialize Late Variables in Kotlin

Last updated: November 29, 2024

In Kotlin, a language widely used for Android development and modern programming due to its expressive syntax and null safety features, the concept of late initialization can be common. This is particularly useful when you have properties in a class that cannot be initialized in the constructor. In this article, we'll look at how to declare and initialize lateinit and lazy variables in Kotlin.

Using lateinit

The lateinit modifier allows you to tell Kotlin that a certain variable will be initialized later, after its declaration. This modifier is only applicable to var properties and not val. It is often used with non-null properties whose value will be assigned at some point in the lifecycle, especially in frameworks like Android for view binding or dependency injection.

class SampleClass {
    lateinit var someString: String
    
    fun initializeString() {
        someString = "Kotlin is awesome!"
    }
}

With lateinit, you need to be cautious: accessing a lateinit variable before it is initialized will result in an UninitializedPropertyAccessException.

Using lazy

The lazy keyword in Kotlin is another way to delay the initialization of a variable, using val properties. It delegates the variable's initialization until it is accessed for the first time. Once it's accessed, the result is stored and returned subsequently.

class SampleClass {
    val someNumber: Int by lazy { computeExpensiveValue() }
    
    private fun computeExpensiveValue(): Int {
        println("Computing...")
        return 42
    }
}

fun main() {
    val sample = SampleClass()
    println("First access: ")
    println(sample.someNumber) // Computation occurs here
    println("Second access: ")
    println(sample.someNumber) // Uses the cached value
}

In this example, the output would be:

Computing...
First access: 
42
Second access: 
42

The lazy initialization is particularly useful when your property initialization is time-consuming or resource-intensive. It's a thread-safe implementation by default, making it suitable for multiple-threaded situations.

Comparing lateinit and lazy

  • lateinit requires that you initialize before use and is mutable (var), while lazy is immutable once initialized (val).
  • lateinit is typically used for non-primitive properties, whereas lazy can be used for any property type.
  • Choose lateinit if you need to use dependency injections, unit tests or frameworks that require non-null properties.

By using lateinit or lazy, Kotlin developers can manage their application's memory usage and performance more effectively, especially when working with objects that require delayed initialization.

Next Article: Organizing Kotlin Code with Packages

Previous Article: Mutable Variables: When to Use `var`

Series: Basics of Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin