CodeGym /Courses /Kotlin SELF /Initialization order: properties → init → secondary con...

Initialization order: properties → init → secondary constructor body

Kotlin SELF
Level 31, Lesson 3
Available

1. Introduction

Initialization order is like the sequence of steps when cooking: if you put the cake in the oven first and only then remember the batter is still in the bag, you get… experimental cuisine. Programming is the same: if in init you use a property that is not initialized yet, or you assume the secondary constructor body will “have time to prepare the data,” you’ll get weird values, extra computations, or exceptions in unexpected places.

This lecture helps you confidently answer questions like: why one println() prints before another, why a validation triggers before your code in a secondary constructor, why a property already has a value inside init, and where it’s best to place a computation so it runs exactly once and at the right moment.

2. Mental model: what object creation consists of

When we write val e = Expense(...), it looks like one line. But in reality, creating an object is a multi-step script, and Kotlin executes those steps in a fixed order. The calmest way to treat it is like a small conveyor: first properties are prepared (initializers), then init blocks run, and only after that (if you create the object via a secondary constructor) its body runs.

The idea is: init blocks execute when an instance is created and go in order, just like property initializers. And if a secondary constructor delegates to the primary (and when a primary exists it must do so), then all initialization (properties + init) is guaranteed to complete before the code in the secondary constructor body.

Let’s lock in the scheme.

flowchart TD
    A["Constructor call: ClassName(...)"] --> B["Delegation to primary constructor (if needed)"]
    B --> C["Property initializers (in the order in the class)"]
    C --> D["init blocks (in the order in the class)"]
    D --> E{"Was creation done via a secondary constructor?"}
    E -->|yes| F["Secondary constructor body { ... }"]
    E -->|no| G["Object is ready"]
    F --> G

And one more short table so it’s convenient to “check at a glance”:

Class part Where we write it When it runs
Property initializer
val x = ...
Before init, in the order declared in the class
init { ... }
init { ... }
After property initializers, also top to bottom
Secondary constructor body
constructor(...) : this(...) { ... }
After properties + init have run

One more useful reference point: assignments of properties from primary constructor parameters conceptually happen before property initializers and init blocks. That’s why the line “looks like one,” but there are many steps inside.

3. Property initializers: earlier than you think

A property initializer is the expression to the right of = when declaring a property. It looks like “we just set a value,” but semantically it’s a piece of code that executes while the object is being created. So you should treat initializers as part of construction: they should be simple, predictable, and not turn object creation into a 12-season TV series.

The most common beginner surprise: “I thought init runs first, and then properties get initialized.” In practice, it’s the opposite: property initializers run before init. This makes init a convenient place where you can safely use values of those properties (if they’re declared above in the code and don’t depend on something “dangerous”).

A property that depends on a constructor parameter

Let’s continue the training console mini-project “expense tracking” (a hypothetical ExpenseTracker). Today we’ll build a small piece of the model so it demonstrates initialization order.

class Expense(rawTitle: String, val amountCents: Int) {
    val title: String = rawTitle.trim()
    val titleLength: Int = title.length

    init {
        println("init: title='$title', length=$titleLength")
    }
}

fun main() {
    Expense("  Coffee  ", 350)
    // init: title='Coffee', length=6
}

The trick here is that titleLength depends on title, and title depends on the rawTitle parameter. Kotlin allows this: primary constructor parameters are available in property initializers and in init.

When the object is created, Kotlin will compute title first, then titleLength, and then execute init. The order goes top to bottom through the class body: as written, so executed.

Hidden work inside a property initializer

Problems start when a property initializer doesn’t just compute a number/string but does “something with side effects”: prints, touches files, goes to the network (yes, people manage to do that too), or depends on something that isn’t ready yet.

Let’s intentionally make initialization “noisy” to see the order:

class DebugExpense(val rawTitle: String) {

    val title: String = normalizeTitle()

    init {
        println("init: title='$title'")
    }

    private fun normalizeTitle(): String {
        println("property init: normalizeTitle()")
        return rawTitle.trim()
    }
}

fun main() {
    DebugExpense("  Taxi  ")
    // property init: normalizeTitle()
    // init: title='Taxi'
}

Notice: first the print from normalizeTitle() (that’s the initializer of the title property), then the print from init. That’s the “conveyor mechanics.”

If you’re used to thinking “init is the main initialization place,” then yes: it’s important. But property initializers are just as real a part of the process; they just often look harmless.

4. init blocks: assemble and validate

An init block is code that runs when an object is created, as part of initialization. It’s usually used for two things: normalizing/preparing state and validating input correctness.

In Kotlin, you can have multiple init blocks, and they execute in the order they appear in the class body, together with property initializers. That sounds simple, but in real code a common question is: “if there are several init blocks, which one runs first?” or “if I declared a property below, can I use it above?” Let’s look at clear traces with println().

One init and a trace print

Let’s build a minimal “order tracker”:

class BuildOrder(val x: Int) {

    val y: Int = x + 1

    init {
        println("init: x=$x, y=$y")
    }
}

fun main() {
    BuildOrder(10)
    // init: x=10, y=11
}

Here you can see that y has already been computed by the time we enter init. That’s expected: property initializers go first.

Multiple init blocks: top-to-bottom order

Now let’s make two init blocks and add a property between them. This is a good technique to “feel” that the order is textual: top to bottom in the file.

class ManySteps(val name: String) {

    init {
        println("init #1: name='$name'")
    }

    val upper: String = name.uppercase()

    init {
        println("init #2: upper='$upper'")
    }
}

fun main() {
    ManySteps("Ann")
    // init #1: name='Ann'
    // init #2: upper='ANN'
}

The practical takeaway is simple: if the second init relies on a property, make sure that property is declared above it. Otherwise you either won’t be able to access it, or you’ll end up with a structure that’s hard to read and maintain.

5. Secondary constructor: why its body is always last

A secondary constructor is often perceived as “an alternative way to create an object,” and that’s true. But the key nuance is when exactly its body executes.

Beginners sometimes expect that they can “prepare data in the secondary constructor body, and then init will run.” Kotlin has a different contract: a secondary constructor must first delegate to the primary (this(...)) if a primary constructor exists, and only after property initializers and init blocks have run does the secondary constructor body execute.

This is done so the class has a single initialization path: the object should not exist “half ready.”

Delegation to primary: a live example

Let’s take Expense and add a secondary constructor that accepts the amount as a string (as if we read user input).

class Expense(val title: String, val amountCents: Int) {

    init {
        println("init: title='$title', amount=$amountCents")
    }

    constructor(rawTitle: String, amountText: String) : this(
        title = rawTitle.trim(),
        amountCents = amountText.toIntOrNull() ?: 0
    ) {
        println("secondary body: amountText='$amountText'")
    }
}

fun main() {
    Expense("  Tea  ", "120")
    // init: title='Tea', amount=120
    // secondary body: amountText='120'
}

The message from init prints earlier than the message from the secondary constructor body. That’s not an accident: delegation guarantees that the core initialization runs before the secondary constructor logic.

And it’s logical: init is part of the object’s “correctness core.” If a secondary constructor could run earlier, you could temporarily hold the object in an invalid state.

A class without a primary: init still runs before the secondary body

Sometimes there is no primary constructor at all, but there is a secondary one. It’s easy to get expectations wrong here too: it may seem that since “there is no primary,” then init should be “after the constructor.” But no: the init block still executes before the secondary constructor body.

class NoPrimary {
    init {
        println("init runs first")
    }

    constructor(x: Int) {
        println("secondary body: x=$x")
    }
}

fun main() {
    NoPrimary(5)
    // init runs first
    // secondary body: x=5
}

If you remember this, you’ll stop “hoping for luck” and start designing initialization deliberately: everything required for correctness goes into the shared path, and the secondary constructor remains an input adapter and, at most, a place for secondary actions (for example, logging), but not for forming the base state.

6. Practical surprises in an expense mini-app

Now let’s tie the mechanics to real meaning. In our console ExpenseTracker, we want Expense to always be valid: the title is not empty, the amount is not negative, and it’s convenient for us to store a “short name” for displaying in a list.

If you place computations in the wrong places, you can get duplication, different values depending on which constructor you used, or just unreadable spaghetti. Next are examples that look a bit “tutorial-like,” intentionally: they show not business logic, but the order of events.

Mistake: hoping a secondary constructor will prepare data for init

Let’s try to make init validate title, while a secondary constructor would like to “fix” the title later. It won’t work (and that’s good).

class BadExpense(val title: String) {

    init {
        require(title.isNotBlank()) { "title must not be blank" }
        println("init: ok")
    }

    constructor(rawTitle: String, allowBlank: Boolean) : this(rawTitle) {
        // Too late! init has already run.
        println("secondary body: allowBlank=$allowBlank")
    }
}

If you create BadExpense(" ", true), then require(...) will fail before the secondary constructor body even begins executing. That’s not a bug; it’s a guarantee: init is part of the shared path.

The correct thought here is: if you need to “fix” input, do it during delegation : this(...) (i.e., before you get into init) or in a property initializer / init on the shared path.

The right pattern: prepare input before init

Let’s make a “normal” version: the secondary constructor brings input to canonical form and passes it to the primary.

class Expense(val title: String) {

    init {
        require(title.isNotBlank()) { "title must not be blank" }
        println("init: title='$title'")
    }

    constructor(rawTitle: String, trim: Boolean) : this(
        title = if (trim) rawTitle.trim() else rawTitle
    )
}

fun main() {
    Expense("  Taxi  ", trim = true)
    // init: title='Taxi'
}

Now it doesn’t matter which path creates the object: init always sees the already prepared title. This matches the idea “secondary is an adapter; primary+init is the single path.”

Order as an API design tool

When you understand the order, it becomes easier to choose where to put logic.

If a computation must be done once and always the same way, it’s convenient to keep it either in delegation parameters (: this(...)), or in a property initializer, or in init. All three places run before the secondary constructor body and form the “base of creation.”

If an action does not affect object correctness (for example, printing a log like “created an expense from a string”), it’s a candidate for the secondary constructor body. This way you don’t pollute the main path and don’t make object creation “too noisy.”

How to debug initialization

When initialization order gets confusing, your brain starts filling in “as if,” and you end up chasing phantom causes. So the best technique is to make the order visible.

The simplest tool is temporary println() calls in property initializers, in init, and in the secondary constructor body. Try to label messages so they are distinct; otherwise later you’ll be reading the log like a cipher.

A good habit is to build a minimal example: one class, one property, one init, one secondary constructor, and a couple of prints. As soon as you see the order in a simple example, transfer the understanding back into the “production” class. Kotlin is predictable here: initializers and init go in declaration order, and the secondary body runs after them.

7. Common mistakes when understanding initialization order

Mistake #1: expecting init to run before property initializers.
It often seems logical: “I wrote init, so everything starts there.” But val x = ... is also initialization code, and it runs before init. Because of this, people are surprised why some computations/prints happen “before the constructor.” The right habit is to treat property initializers as the first phase of object creation, which goes before init.

Mistake #2: thinking the secondary constructor body runs before init and can prepare data.
This is especially common when a secondary constructor accepts a string and wants to “fix” fields, while init already validates correctness. But Kotlin guarantees the opposite: the secondary delegates to the primary, properties and init run, and only then does the secondary constructor body run. If you need to prepare data for init, do it in delegation : this(...).

Mistake #3: hiding heavy work inside a property initializer and then being surprised by performance and logs.
A property initializer looks like an assignment, so sometimes people put computations with side effects there: printing, complex string parsing, generating something large. Then the object “becomes too expensive to create,” and the logs contain lots of messages “by themselves.” It’s better to keep property initializers simple: compute values from already available data without surprises, and put more noticeable logic explicitly in init (or before passing to the primary).

Mistake #4: confusing textual order in code with the logical order in your head.
If the second init uses a property declared below, the compiler won’t let you do that, or you’ll start rearranging pieces at random. Discipline helps: declare properties in the order they are needed, and place init blocks next to the properties whose meaning they ensure. Kotlin executes init blocks top to bottom, and that’s not an “implementation detail,” but part of readability.

Mistake #5: duplicating initialization and validations across multiple constructors.
When a class has multiple secondary constructors, beginners sometimes copy the same require(...) or the same trim() into each constructor body. The result: one constructor didn’t get updated, and the class behavior started depending on the creation method. It’s much more reliable to keep correctness rules in the shared path (in init and/or in delegation to the primary), so all creation paths lead to the same logic.

Mistake #6: turning object creation into a show full of side effects.
Sometimes it’s tempting during creation to print, compute, mutate external variables, and kick off complex scenarios. But object creation should be kept as clean as possible: by the end of init, the object should be ready for use, not “almost ready, just three more steps.” If you need lots of external actions, it’s usually a sign you mixed “model construction” and “application scenario” in one place.

1
Task
Kotlin SELF, level 31, lesson 3
Locked
Normalization trace
Normalization trace
1
Task
Kotlin SELF, level 31, lesson 3
Locked
Build Steps
Build Steps
1
Task
Kotlin SELF, level 31, lesson 3
Locked
Receipt from a form
Receipt from a form
1
Task
Kotlin SELF, level 31, lesson 3
Locked
Log without primary
Log without primary
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION