0
0
KotlinConceptBeginner · 3 min read

What is lateinit in Kotlin: Simple Explanation and Usage

lateinit in Kotlin is a keyword used to declare a variable that will be initialized later, after its declaration. It allows you to avoid null checks for non-nullable types when you are sure the variable will be assigned before use.
⚙️

How It Works

Imagine you have a box that you want to fill later, but you want to tell everyone that the box will definitely be filled before anyone opens it. In Kotlin, lateinit works like that box. It lets you declare a variable without giving it a value right away, but promises that you will assign a value before using it.

This is useful because Kotlin normally requires you to initialize variables when you declare them or mark them as nullable. With lateinit, you avoid making the variable nullable and skip null checks, but you must be careful to initialize it before use, or the program will throw an error.

💻

Example

This example shows how to use lateinit with a variable that is assigned later and then used safely.

kotlin
class User {
    lateinit var name: String

    fun setupName() {
        name = "Alice"
    }

    fun printName() {
        if (this::name.isInitialized) {
            println("User name is $name")
        } else {
            println("Name is not initialized yet")
        }
    }
}

fun main() {
    val user = User()
    user.printName()  // Before initialization
    user.setupName()  // Initialize
    user.printName()  // After initialization
}
Output
Name is not initialized yet User name is Alice
🎯

When to Use

Use lateinit when you have a non-null variable that cannot be initialized at the moment of declaration but will definitely be assigned before use. This often happens with variables that depend on external setup, like views in Android apps or dependencies injected later.

For example, in Android development, UI elements are often declared with lateinit because they are assigned after the layout is loaded, not when the object is created.

Key Points

  • Only for var: lateinit can only be used with var, not val.
  • Non-null types: It works only with non-nullable types.
  • Must initialize before use: Accessing before initialization throws UninitializedPropertyAccessException.
  • Check initialization: Use ::variable.isInitialized to check if it’s set.

Key Takeaways

lateinit lets you declare non-null variables without initializing them immediately.
You must initialize lateinit variables before using them to avoid errors.
It is useful when initialization depends on external factors or setup steps.
Only mutable variables (var) can be lateinit.
Check if a lateinit variable is initialized using ::variable.isInitialized.