Kotlin example

How to check if a lateinit variable is initialized in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Inside the class that declares it, write this::name.isInitialized (or just ::name.isInitialized): it is false until the first assignment and true after. Reading the property before that throws kotlin.UninitializedPropertyAccessException: lateinit property name has not been initialized. The check only compiles where the property's backing field is visible, so expose a val isReady to other classes.

A lateinit var is a non-null property you promise to set before you read it: a view in onCreate, a test fixture in @BeforeEach, a field a dependency-injection framework fills in. Kotlin has no null to compare against, so the way to ask "has it been set yet?" is a property reference and its isInitialized flag. The sections below cover that check, the exception you get when you read too early, where the check does not compile, the rules for lateinit (and what to use for an Int), by lazy versus lateinit, and the Property must be initialized or be abstract error that sends people to lateinit in the first place. Each example runs on this page: hit Run, then edit the code and run it again.

1this::prop.isInitializedRecommended

::title is a reference to the property itself, not its value, and isInitialized on that reference tells you whether a value has been assigned. Reading it never throws. Write it inside the class, either as this::title.isInitialized or with the this left out. A common pattern is a small val that wraps the check, so the rest of the code asks screen.isReady instead of repeating the reference syntax.

IsInitialized.kt
class ReportScreen {
    lateinit var title: String

    // ::title is the property itself; isInitialized says if it has a value
    val isReady: Boolean
        get() = this::title.isInitialized

    fun show() {
        if (::title.isInitialized) {
            println("Showing $title")
        } else {
            println("Title not set yet")
        }
    }

    // Set it only the first time
    fun setDefaultTitle() {
        if (!::title.isInitialized) title = "Untitled report"
    }
}

fun main() {
    val screen = ReportScreen()
    println("ready: ${screen.isReady}")
    screen.show()

    screen.title = "Sales Q4"
    println("ready: ${screen.isReady}")
    screen.show()

    screen.setDefaultTitle()
    screen.show()

    val other = ReportScreen()
    other.setDefaultTitle()
    other.show()
}

Output

A fresh ReportScreen prints ready: false and the else branch runs, with no exception. After screen.title = "Sales Q4" both checks flip to true. setDefaultTitle() leaves the existing title alone on the first screen and fills in Untitled report on the second. There is no way back: once set, a lateinit stays initialized, so if "not set" is a state you need to return to, use a nullable property instead.

2Reading too early: UninitializedPropertyAccessException

Read a lateinit property before it has a value and Kotlin throws UninitializedPropertyAccessException, with the property's name in the message. That is the point of lateinit over a Java-style field: in Java the field would quietly be null and the crash would come later, somewhere else, as a NullPointerException. Here it fails at the read. You can catch it, but it is a bug signal; the fix is to set the property first or check isInitialized.

ReadTooEarly.kt
class Order {
    lateinit var id: String

    fun describe() = "Order $id"
}

fun main() {
    val order = Order()

    try {
        println(order.describe())
    } catch (e: UninitializedPropertyAccessException) {
        println("${e::class.simpleName}: ${e.message}")
    }

    // It is a RuntimeException, like NullPointerException
    val e = UninitializedPropertyAccessException("demo")
    println(e is RuntimeException)

    order.id = "A-1001"
    println(order.describe())
}

Output

The message is lateinit property id has not been initialized, so the log tells you which property was read too early. Uncaught, a run here ends with Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property name has not been initialized and a first trace line such as at User.getName(Main.kt:2): the getter of the property, then the line that called it. On Android this is the classic crash when a view or adapter is used before onCreate or onViewCreated has set it.

3Where isInitialized compiles (and where it does not)

isInitialized needs access to the property's backing field, so it only compiles in the class that declares the property, in classes nested inside it (an inner class or the companion object), or for a top-level lateinit in the same file. Anywhere else (main, another class, a subclass, an extension function), repo::url.isInitialized fails here with Backing field of 'var url: String' is not accessible at this point. A local lateinit var inside a function is allowed, but ::name.isInitialized on it fails with References to variables aren't supported yet. The fix for the first case is a property on the owning class that does the check for its callers.

WhereItWorks.kt
class Repo {
    lateinit var url: String

    // Other classes can't check url, so give them a property
    val hasUrl: Boolean
        get() = ::url.isInitialized

    // Code nested in the class can check any instance
    companion object {
        fun describe(repo: Repo) =
            if (repo::url.isInitialized) repo.url else "(no url)"
    }
}

// A top-level lateinit can be checked in the same file
lateinit var configPath: String

fun main() {
    val repo = Repo()
    println("hasUrl = ${repo.hasUrl}, ${Repo.describe(repo)}")

    repo.url = "https://example.com/app.git"
    println("hasUrl = ${repo.hasUrl}, ${Repo.describe(repo)}")

    println("configPath set: ${::configPath.isInitialized}")
    configPath = "/etc/app.conf"
    println("configPath set: ${::configPath.isInitialized}")
}

Output

main never touches url's state directly; it asks repo.hasUrl, which flips from false to true, and the companion object checks the instance it is given. The top-level configPath works with a plain ::configPath. For a local variable, skip lateinit and use var name: String? = null with a null check: it says the same thing and you can test it anywhere.

4The lateinit rules, and Delegates.notNull() for Int

lateinit works only on a var of a non-null type that is not a primitive, with no initializer and no custom getter or setter. Break a rule and the error says which: lateinit val gives 'lateinit' modifier is allowed only on mutable properties., lateinit var count: Int gives 'lateinit' modifier is not allowed on properties of primitive types., and lateinit var name: String? gives 'lateinit' modifier is not allowed on properties of a type with nullable upper bound. (the same error appears for a generic T; declare it T : Any). For Int, Long, Double or Boolean, use Delegates.notNull(): it behaves like lateinit but has no isInitialized check. For a value that may legitimately be missing, use a nullable type.

NotNullDelegate.kt
import kotlin.properties.Delegates

class Player {
    // lateinit var score: Int does not compile; this is the stand-in
    var score: Int by Delegates.notNull()

    // A value that may be missing: nullable, starts as null
    var nickname: String? = null
}

// lateinit works for a generic type once T is non-null
class Slot<T : Any> {
    lateinit var item: T
    fun isFilled() = ::item.isInitialized
}

fun main() {
    val player = Player()
    try {
        println(player.score)
    } catch (e: IllegalStateException) {
        println("${e::class.simpleName}: ${e.message}")
    }
    player.score = 120
    println("score = ${player.score}")
    println("nickname = ${player.nickname ?: "none"}")

    val slot = Slot<Int>()
    println("filled: ${slot.isFilled()}")
    slot.item = 7
    println("filled: ${slot.isFilled()}, item = ${slot.item}")
}

Output

Reading score before it is set throws IllegalStateException: Property score should be initialized before get., the notNull() version of the lateinit exception. The Slot class shows that a Slot<Int> is fine: the rule is about the declared type T, and T : Any rules out null. The check sits inside the class, as in section 3.

5by lazy vs lateinit

Both delay a value, but they answer different questions. by lazy is for a val whose value the class can compute itself: the block runs on the first read and the result is kept. lateinit is for a var that something outside sets later (a framework, a test, a setup call) and that may change. A lazy value can be any type, including Int and nullable types, and can never be read "too early". To ask whether it has run yet, keep the Lazy object and call its isInitialized() function.

LazyVsLateinit.kt
class Dashboard {
    // by lazy: a val computed on first read, then cached
    val report: String by lazy {
        println("  building report...")
        "42 orders"
    }

    // lateinit: a var that someone else sets later
    lateinit var user: String
}

fun main() {
    val board = Dashboard()
    println("created")
    println(board.report)
    println(board.report)

    board.user = "ada"
    board.user = "grace"
    println("user = ${board.user}")

    // Keep the Lazy object to ask if it has run
    val total = lazy(LazyThreadSafetyMode.NONE) { 6 * 7 }
    println("computed: ${total.isInitialized()}")
    println("value: ${total.value}")
    println("computed: ${total.isInitialized()}")
}

Output

building report... prints once, between created and the first 42 orders; the second read uses the cached value. user takes two assignments and ends as grace, which a val by lazy could not do. By default lazy is SYNCHRONIZED: if several threads read it at once, one runs the block and the others wait for its result. LazyThreadSafetyMode.PUBLICATION lets several threads run the block and keeps the first value stored, and NONE, used above, skips locking altogether, for values only one thread touches. lateinit has no locking of its own.

6The error: “Property must be initialized or be abstract”

In Java an unassigned field starts as null. Kotlin has no such default: every non-abstract property needs a value from an initializer, the constructor or an init block, or the class does not compile. The program below never runs, because name has a type and nothing else.

MustBeInitialized.kt
class User {
    var name: String

    fun greet() = "Hi, $name"
}

fun main() {
    println(User().greet())
}

Output

The compiler stops with Property must be initialized or be abstract. at line 2 (a val gets the same message). Pick the fix that matches the data: a default (var name = ""), a constructor parameter (class User(var name: String)), a value set in init { }, var name: String? = null if it can be missing, by lazy for a val the class can compute, or lateinit var when something sets it after construction. Prefer the constructor when the caller has the value; lateinit trades this compile-time check for a run-time exception.

7Which should you use?

DeclarationRead before setCheck if setBest for
class User(val name: String)ImpossibleNot neededValues the caller has when it creates the object
val x by lazy { … }Computes itLazy.isInitialized()Costly values the class can compute itself
lateinit var x: TUninitializedPropertyAccessException::x.isInitializedNon-null values set by a framework, a test or a setup call
var x: Int by Delegates.notNull()IllegalStateExceptionNonePrimitives set after construction
var x: T? = nullGives nullx != nullValues that can be missing or reset

Frequently asked questions

How do I check if a lateinit variable is initialized in Kotlin?

Use a property reference: this::name.isInitialized, or ::name.isInitialized inside the class. It returns false until the property has been assigned and true after, and it never throws. It compiles only in the class that declares the property, in classes nested in it, or for a top-level lateinit in the same file.

Why do I get "Backing field is not accessible at this point"?

You called isInitialized on a property from outside the class that declares it, for example repo::url.isInitialized in another class, a subclass or an extension function. Here the error reads Backing field of 'var url: String' is not accessible at this point. Add a property to the owning class, such as val hasUrl get() = ::url.isInitialized, and call that instead.

What is the difference between lateinit and by lazy?

lateinit goes on a var of a non-null, non-primitive type that code outside sets later; reading it first throws UninitializedPropertyAccessException. by lazy goes on a val: the class gives a block that runs on the first read, and the result is cached. Use lazy when the class can compute the value itself, lateinit when a framework, test or setup method provides it.

Is by lazy thread-safe?

Yes by default. lazy { … } uses LazyThreadSafetyMode.SYNCHRONIZED: the block runs once, and other threads wait for the result. lazy(LazyThreadSafetyMode.PUBLICATION) lets several threads run the block and keeps the first value stored, and LazyThreadSafetyMode.NONE skips locking for values used from one thread only. lateinit has no synchronization at all.

Can I use lateinit with Int or other primitive types?

No. lateinit var count: Int fails with 'lateinit' modifier is not allowed on properties of primitive types. The same holds for Long, Double, Boolean and the other primitives. Use var count: Int by Delegates.notNull(), which throws IllegalStateException when read before it is set, or var count: Int? = null if you need to check it.

Why can't a lateinit property be nullable or a val?

Kotlin uses null internally to mark a lateinit field as not set yet, so the type itself cannot allow null; a nullable var can simply start as null instead. It must be a var because the value arrives by assignment after construction, which a val does not allow. For a read-only value computed later, use val x by lazy { … }.

How do I reset a lateinit variable?

You can't: once a lateinit property has a value, isInitialized stays true and there is no way to make it unset. If "not set" is a state you need to go back to, for example after logout or when a screen is destroyed, declare it nullable (var session: Session? = null) and assign null.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground