Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 134 ยท Classes and Objects

lateinit vs lazy

Compare Kotlin lateinit and lazy: when each initializes, their rules and errors, isInitialized, thread safety, nullable alternatives, and a simple way to choose between them.

Kotlin's null safety wants every non-null property to have a value as soon as an object exists. Real programs do not always cooperate. A value may only be known after a framework has created your object, or it may be so expensive to build that you want to wait until someone actually needs it. Kotlin offers two standard answers: lateinit and lazy. They look similar from the outside, because both let you declare a non-null property without initializing it in the constructor. They are in fact very different tools.

This lesson puts them side by side. You will learn who provides the value in each case, what errors they produce, what each one forbids, and how to choose. It assumes you know null safety, properties and have seen the standard delegates in Delegated Properties.

The core difference

The easiest way to remember it is to ask: who decides the value, and when?

  • With lateinit, someone else sets the value later, from outside, by assignment. You promise the compiler it will happen before the first read.
  • With lazy, the property itself knows how to compute its value, and does so automatically on the first read.
flowchart TD
    Q{"Property needs a value<br/>after construction?"} -->|"Value is computed<br/>by the property itself"| L["by lazy<br/>val, computed on first read"]
    Q -->|"Value is assigned later<br/>by outside code"| M{"Type is a primitive<br/>or nullable?"}
    M -->|"No"| LI["lateinit var"]
    M -->|"Yes"| N["var x: T? = null<br/>or Delegates.notNull()"]

A quick decision path: self-computed values use lazy; values assigned from outside use lateinit or a nullable property.

lateinit in practice

lateinit is a modifier on a var. The property has no value until you assign one. Reading it earlier throws UninitializedPropertyAccessException, and you can check with ::name.isInitialized first:

Kotlin lateinit: assigned later, checked with isInitialized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The typical home for lateinit is code where another system creates your object and then injects values: a dependency injection framework, an Android view that is created in onCreate, or a test class whose setup method runs before each test. In those cases a nullable property would force a ?. or !! on every use, even though you know the value is there.

The rules of lateinit

The compiler enforces a list of restrictions, and each one has a reason:

Rule Why
Only on var The value is assigned after construction, so it must be mutable
Not on primitives (Int, Boolean, ...) A primitive cannot represent "not set"
Not on nullable types null would be an ambiguous "not set" marker
No initializer The whole point is that there is none
No custom getter or setter The compiler needs direct field access to check initialization

Here is what the compiler says if you break them. These are the real messages:

TEXT
'lateinit' modifier is not allowed on properties of primitive types.
'lateinit' modifier is allowed only on mutable properties.
'lateinit' modifier is not allowed on properties of a type with nullable upper bound.
'lateinit' modifier is not allowed on properties with a custom getter or setter.

lateinit also works for top-level properties and for local variables, and isInitialized can be used on any of them in the same scope where they are declared (it is only accessible from code that can see the backing field, so you cannot call it from another class).

lazy in practice

lazy is not a modifier but a delegate function. It takes a lambda, runs it on first access, and remembers the result. The property is a val:

Kotlin lazy: computed by the property, on first read

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Nobody assigns summary. The class already contains everything needed to produce it, and the cost is paid only if somebody reads it. Because the value is cached and never changes, the property is a val. It is also thread safe by default, which lateinit is not: two threads racing to initialize a lateinit property can overwrite each other, while lazy makes sure its block runs only once.

Seeing both in one class

The following class contains one of each, plus a nullable property for comparison. Watch when each resource is opened:

Kotlin lateinit, lazy and nullable in one class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Reading the output top to bottom tells the whole story. Construction opens nothing. load() opens the header, because that is where we wrote the assignment. The body opens at the first read and never again. The footer is a different category: it is optional, so the type says so, and every use is checked by the compiler. The last line shows the failure when a lateinit property is read before anyone set it.

Comparison table

lateinit var val x by lazy { }
Who provides the value Outside code, by assignment The initializer lambda
When Any time before first read At first read
Mutable Yes No (val), though lazy can back a var only with custom delegates
Can be reassigned Yes No
Primitive types Not allowed Allowed
Nullable types Not allowed Allowed (the lambda may return null)
Error when misused UninitializedPropertyAccessException Exceptions in the lambda propagate; retried on next read
Thread safe No Yes by default
Check if set ::prop.isInitialized Lazy.isInitialized() on the Lazy object
Cost A null check on each read A delegate object and a lock

Choosing well

Prefer lazy when the initializer is part of the class: a parsed config, a compiled regex, a heavy collection, a connection that is only sometimes used. It documents how the value is made and guarantees it is made once.

Prefer lateinit when the value comes from outside and cannot be passed through the constructor: dependency injection fields, framework callbacks, test fixtures. Keep these properties to a minimum; every lateinit is a promise the compiler cannot verify.

Prefer constructor parameters over both when you can. A property set in the constructor is always valid, needs no checks and is the easiest to test. Many lateinit fields are really a sign that an object is built in two steps (create, then configure) where a single step would be safer.

Prefer a nullable var when absence is a legitimate state your code should handle, such as an optional footer. lateinit means "never absent after setup"; ? means "may be absent".

Use Delegates.notNull() for the case that lateinit does not cover: a late-assigned property of a primitive type such as Int.

Do not "fix" a lateinit error by turning the type nullable and sprinkling !! through the code. If the value must exist, find out why it is missing; if it may be missing, handle that explicitly with ?. and ?:. Both are better than a NullPointerException later.

A look at a test fixture

A common legitimate use is a test class. The framework creates the object, then calls the setup method before each test, so the constructor cannot receive the value:

Kotlin
class CartTest {
    private lateinit var cart: Cart

    @BeforeTest
    fun setUp() {
        cart = Cart()
    }

    @Test
    fun startsEmpty() {
        assertTrue(cart.isEmpty())
    }
}

This sketch is read-only because the runner has no test framework; see Testing Basics for a runnable version. It illustrates the pattern: the setup method promises to assign the property before any test reads it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement best describes lateinit?

    lateinit defers initialization to some later assignment from outside the declaration. Reading it before that point throws UninitializedPropertyAccessException.
  2. 2. Why can't lateinit be used with an Int property?

    lateinit relies on the field holding null to mean not initialized. Primitives have no null, so the modifier is rejected; use Delegates.notNull() instead.
  3. 3. A configuration object is expensive to build and might never be used. Which declaration fits best?

    lazy defers the cost until the first read, runs the loader once, and needs no outside code to set the value.
  4. 4. How do you check whether a lateinit property named token has been assigned?

    A lateinit property is checked through its property reference with ::token.isInitialized. You can't compare it with null because its type is non-null.
  5. 5. Which is thread safe by default?

    lazy uses a synchronized strategy by default so its block runs once. lateinit does no synchronization at all.

Summary

  • lateinit var promises that outside code will assign a non-null value before the first read; reading too early throws UninitializedPropertyAccessException.
  • lateinit is not allowed on primitives, nullable types, val, properties with initializers or custom accessors.
  • val x by lazy { ... } computes the value once on first read, is thread safe by default and has no assignment.
  • Use lazy for self-computed expensive values, lateinit for injected or framework-set values, and a nullable type when absence is valid.
  • Constructor parameters are safer than either; reach for these tools only when construction cannot supply the value.

Next: Generics