CodeBlanks Logo Icon CodeBlanks

lateinit

Learn deferred initialization with lateinit var.

lateinit

Sometimes you cannot give a variable its value right away; for example, a configuration might load later. With lateinit var you declare the variable now and assign its value later.

lateinit works only with var and only for reference types (e.g., String, class instances); it cannot be used for primitive types (Int, Double).

lateinit var config: String

fun main() {
    config = "active"
    println(config)
}

Practice Initialize lateinit

At the top level, declare lateinit var config: String. Inside fun main(), first assign config = "active", then print with println(config).

Sample solution

Main.kt
lateinit var config: String

fun main() {
    config = "active"
    println(config)
}

Expected output

active

lateinit safety

If you access a lateinit variable before assigning a value, Kotlin throws UninitializedPropertyAccessException. To prevent this, you can check whether it has been initialized with ::config.isInitialized.

This is especially useful in dependency-injection frameworks, where objects are wired later during setup. So lateinit is common in the pattern of declaring first, initializing after injection.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 lateinit: match the terms

Term Meaning
lateinit Assigned later
var Mutable
val Immutable
const val Compile-time

2 Which can lateinit NOT be used with?

  • String
  • Int Correct answer
  • A class instance
  • List

Explanation: lateinit cannot be used with primitive types like Int or Double.

3 lateinit: fill in the missing part

Question
lateinit var config: ____
Answer
lateinit var config: String

Explanation: lateinit works with reference types like String.

All lessons in Beginner