CodeGym /Courses /Kotlin SELF /lateinit — deferred initialization and safe class API des...

lateinit — deferred initialization and safe class API design

Kotlin SELF
Level 32, Lesson 2
Available

1. Why you need lateinit

Sometimes you need to create an object right away, but the data for it will appear only later — according to the program’s workflow. For example, you are writing a console application: the user starts the program, it creates the application “core”, and only then asks questions: name, currency, operating mode, etc. From the code’s point of view, you get a situation where the object already exists, but some of its important fields will appear only after a dialog with the user. And you want those fields to be non-null, because “if the currency is not set, the app simply makes no sense”.

A typical beginner’s dilemma looks like this: either make the field nullable (String?) and then write checks everywhere, or assign some “temporary” value like "UNKNOWN" and then hope you won’t forget to replace it with the real one. And this is where Kotlin offers a tool that sounds like a magic spell from Hogwarts: lateinit.

The problem: the object already exists, but the data is not there yet

Imagine you bought a kettle (the object is created), but you haven’t poured water in yet (the property isn’t ready). A kettle without water is fine, but you must not turn it on. And a good API design should prevent “turning on an empty kettle”.

lateinit as an “initialized later” contract

It’s important to catch the main idea before your hand reaches for lateinit in every class “just in case”. lateinit is not a way to “trick Kotlin”; it is a way to explicitly record a contract: “this property will definitely be set, but not at the moment the object is created”. That is, you do not make the field nullable; you say: “it will be non-null, just a bit later”.

When you use lateinit, you declare a property var without initialization, while promising it will be set later (usually by a separate method, or by external logic that is guaranteed to run). Kotlin allows this, but the responsibility for the correct order of actions is shifted to you.


class Config {
    lateinit var apiKey: String
}

Here apiKey is not nullable (String, not String?), but when Config() is created it is not set yet. Later you will do config.apiKey = "...".

Limitations of lateinit

lateinit has several limitations, and they are not due to compiler “spite”, but because otherwise the behavior would become too “magical” and dangerous.

lateinit can be used only if:

What we want Can we use lateinit? Why
lateinit var name: String
Yes Non-null reference type; it can be assigned later
lateinit var list: MutableList<String>
Yes Also a non-null reference type
lateinit val token: String
No val cannot be assigned later — it must be set immediately
lateinit var count: Int
No For primitives (Int, Double, Boolean) lateinit does not work
lateinit var x: String?
No (and you don’t need it) If null is allowed, it is simpler and more honest to use a nullable type

The fact that lateinit does not work for Int often surprises people. But if you think about it: Kotlin cannot “store the absence of a value” inside an Int without some special marker. References have a natural “no value” marker — null — but for Int there is no such “empty state” (at least at the level of the Kotlin contract).

Why lateinit almost always needs an explicit type

You won’t have a value on the right-hand side, so Kotlin will not be able to infer the type from initialization. That’s why you must specify the type explicitly — it’s the same principle we already saw for variables without an initial value.

Compare:

val x = 10          // the type will be inferred automatically
val y: Int          // without initialization, the type is mandatory

With lateinit it is the same idea, just inside a class:

class Session {
    lateinit var currency: String
}

What happens if you access a lateinit too early

lateinit is not a “soft” construct. It is very honest: if you violate the contract (read the property before assigning it), the program crashes with a runtime error. And this is actually good news: the error shows up immediately instead of turning into silent data corruption.

Let’s see what it looks like in a mini example. Here I do it intentionally the wrong way so you can see the symptom.

class Profile {
    lateinit var userName: String
}

fun main() {
    val p = Profile()

    // We forgot p.userName = "..."
    println(p.userName) // Boom
}

In real life this usually manifests as an exception like “property ... has not been initialized”. If you start “treating” it with try/catch, you’ll just mask the bug: the application will continue running in an invalid state. So the normal strategy is not to “catch the crash”, but to design the API so that the crash cannot happen.

2. Safe API design with lateinit

When lateinit appears, a second question almost always appears too: “How do I make sure nobody (including me a week from now) can call methods in the wrong order?” That’s API design. We want using the object to look like a clear scenario: first prepare, then work. And if the scenario is violated, we get fail-fast with a good message.

Here require(...) and check(...) help a lot: the first is about validating input arguments; the second is about validating the object’s state.

Pattern: init(...) + check(...)

The pattern is simple: you keep lateinit inside, and expose an init(...) method that transitions the object into a “ready” state. All methods that require readiness start with an internal check(...).

class AnalyticsClient {
    private var ready: Boolean = false
    lateinit var apiKey: String
        private set

    fun init(key: String) {
        require(key.isNotBlank()) { "apiKey must not be blank" }
        apiKey = key
        ready = true
    }

    fun send(event: String) {
        check(ready) { "AnalyticsClient is not initialized. Call init(...) first." }
        println("Send '$event' with apiKey=$apiKey")
    }
}

Notice: we do not allow external code to assign apiKey (it has a private set), initialization goes through init(...). And check(...) is an explicit guard at the door that won’t let you call methods too early.

Why lateinit is better kept inside the class

A very common beginner mistake is to make a public lateinit var and then assign it from anywhere. It is convenient for exactly one minute while the project is small. Then you accidentally assign the wrong thing, or forget to assign, or assign twice — and you start a fun quest: “why is it crashing?”

Try to think like this: lateinit is an internal detail, not a “button for everyone”. That’s why most of the time it should be private, or at least have a private set, with methods on the outside that guarantee the scenario is correct.

require(...) and check(...): who is responsible for what

It’s easy to mix them up, so let’s say it in plain language.

  • require(...) is used when the user (or calling code) passed you an invalid argument: an empty string, a negative number, an unsupported format. This is an “input error”.
  • check(...) is used when the arguments are fine, but the object is currently in an inappropriate state. For example, you did not call init(...) but you are trying to send(...). This is a “scenario/logic error”.

And yes, these checks are not “being mean to the user”, but a way to make the code predictable. After all, the computer will break everything anyway — you can just choose where exactly it breaks.

3. Practical example: the BudgetBuddy console expense tracker

So that lateinit doesn’t remain an “abstract thing from a textbook”, let’s embed it into a small piece of a console application. Let’s imagine we are making a simple expense helper: the user starts the program, enters a name and a currency, and then adds expenses. The name and currency must be mandatory, but they appear only after launch and a dialog.

We will create a BudgetBuddySession class: it is created immediately, but becomes usable only after init(...).

Expense model Expense

Let’s start with a very simple expense model. We need it so there is something to store in the list and print. No tricks here: data and a bit of convenience for output.

data class Expense(
    val title: String,
    val amountCents: Int
) {
    init {
        require(title.isNotBlank()) { "title must not be blank" }
        require(amountCents > 0) { "amountCents must be > 0" }
    }
}

require(...) here is about validating input when creating the object: an expense with an empty title and an amount of 0 is suspicious, like a “100% discount” in a store.

BudgetBuddySession: lateinit for data that appears after startup

Now the “session” itself. It will contain the user’s name, the currency, and the list of expenses. The name and currency are mandatory, but set later, so we make them lateinit. At the same time, we close off writing from the outside.

class BudgetBuddySession {
    private var ready: Boolean = false

    lateinit var userName: String
        private set

    lateinit var currency: String
        private set

    private val expenses = mutableListOf<Expense>()

    fun init(userName: String, currency: String) {
        require(userName.isNotBlank()) { "userName must not be blank" }
        require(currency.isNotBlank()) { "currency must not be blank" }

        this.userName = userName.trim()
        this.currency = currency.trim().uppercase()
        ready = true
    }
}

Notice: we use trim() and uppercase() right inside init(...) so the internal state is normalized. This reduces the chance that later you’ll compare "usd" and "USD" and wonder why they are not equal.

Methods that require readiness

The next step is to give the session operations: add an expense and print the list. And here is an important technique: don’t smear checks across the whole class; instead, create a small private method ensureReady() and call it where needed.

class BudgetBuddySession {
    private var ready: Boolean = false

    lateinit var userName: String
        private set
    lateinit var currency: String
        private set

    private val expenses = mutableListOf<Expense>()

    fun init(userName: String, currency: String) {
        require(userName.isNotBlank()) { "userName must not be blank" }
        require(currency.isNotBlank()) { "currency must not be blank" }

        this.userName = userName.trim()
        this.currency = currency.trim().uppercase()
        ready = true
    }

    private fun ensureReady() {
        check(ready) { "Session is not initialized. Call init(...) first." }
    }

    fun addExpense(title: String, amountCents: Int) {
        ensureReady()
        expenses.add(Expense(title, amountCents))
    }

    fun printAll() {
        ensureReady()
        println("Expenses of $userName ($currency):")
        expenses.forEach { println("- ${it.title}: ${it.amountCents} cents") }
    }
}

Here check(...) is exactly a state check. If you forgot to call init(...), the object is not “ready” yet, and the methods honestly tell you so.

Usage in main

Now let’s assemble a small scenario. We create a session, ask the user for a name and a currency, call init(...), and then use the methods.

fun main() {
    val session = BudgetBuddySession()

    print("Your name: ")
    val name = readln().trim()

    print("Currency (e.g., USD): ")
    val currency = readln().trim()

    session.init(name, currency)

    session.addExpense("Coffee", 450)
    session.addExpense("Sandwich", 899)

    session.printAll()
    // Expenses of Alice (USD):
    // - Coffee: 450 cents
    // - Sandwich: 899 cents
}

From the outside it looks like a normal contract: first initialization, then work. We don’t allow someone to accidentally do session.currency = "LOL" in the middle of the program — the property has a private set.

4. When lateinit is appropriate

There is a dangerous moment: as soon as you learn lateinit, your brain starts seeing it as a universal key to all doors. But lateinit is not a universal key; it’s more like a side entrance you use when the main entrance is closed for objective reasons.

The main rule is: if a value is mandatory and known at construction time, pass it through the constructor. If a value may be absent by design, use a nullable type. If a value is mandatory but appears later due to the workflow, then lateinit is a candidate.

A small “navigator” table:

Situation Better like this Why
The value is mandatory and known immediately constructor (val x: ...) The object is valid right away
The value may be absent by meaning T? “no value” is part of the contract
The value is mandatory, but will arrive later lateinit var + explicit init(...) Two-stage readiness, but without null
The value is computed on first use lazy (in the next lecture) A different mechanism: computation + caching

Note that I said exactly enough about lazy to avoid confusing it with lateinit: it is not “assign later”, but “compute later”. We’ll cover it in detail in the next lecture.

5. Common mistakes when working with lateinit

Mistake #1: using lateinit “so you don’t have to think”.
The most common reason lateinit appears in the wrong places is the desire to avoid choosing between a constructor and nullable. But lateinit does not remove the need to think; it just shifts responsibility to call order. If the value should always be known when the object is created, it is much cleaner to pass it into the primary constructor and not give the object a “teenage phase” where it exists but still doesn’t know who it is in life.

Mistake #2: making a public lateinit var and allowing assignment from anywhere.
This makes you lose control over the state: someone assigned it, someone overwrote it, someone forgot, someone assigned an empty string. lateinit should almost always be hidden: private or at least with a private set, and the outside world should interact with the object via methods like init(...), where you can normalize and validate the data.

Mistake #3: checking readiness “wherever” instead of one explicit contract.
Sometimes the code turns into a patchwork quilt: one method has a check, another forgot, a third uses a different check. As a result, the object behaves unpredictably. It is much more stable to keep a single control point: either a private ensureReady() with check(...), or a strict rule that public methods are available only after init(...).

Mistake #4: trying to “fix” the issue with try/catch and continuing execution.
If you read a lateinit property before initialization, that is not an “expected input error”; it is a broken scenario. Catching the exception and continuing almost always means “we’ll keep going in an invalid state and break something else later, just in a different place”. For such situations, fail-fast is better: check(...) with a clear message.

Mistake #5: mixing up require(...) and check(...) and getting weird messages.
When the user entered an empty name — that’s an argument, and require(...) fits better. When you forgot to call init(...) and jumped into addExpense(...) — that’s state, and check(...) fits better. If you mix them up, error messages will be misleading: you will “blame the user” for the fact that it was you who skipped the initialization step (or vice versa).

1
Task
Kotlin SELF, level 32, lesson 2
Locked
Late greeting
Late greeting
1
Task
Kotlin SELF, level 32, lesson 2
Locked
App business card
App business card
1
Task
Kotlin SELF, level 32, lesson 2
Locked
URL client
URL client
1
Task
Kotlin SELF, level 32, lesson 2
Locked
Notes session
Notes session
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION