# When Does the init Block Run in Kotlin?

> **In short:** An `init` block runs every time you create an object, as part of the primary constructor. Property initializers and `init` blocks run from top to bottom, in the order you wrote them. A secondary constructor's own body runs after all of them.

Most Kotlin developers know that `init` runs when an object is created. Fewer know that it runs in the middle of your properties, not after them.

Say you write a `Profile` class. You add a property, then an `init` block that prints the profile, then a second property below it. The app runs, and the log shows `greeting = null` for a property of type `String`. A `String` can't be null. There was no compile error and no warning.

This post covers when `init` runs, the order rule behind that `null`, `lateinit` inside `init`, secondary constructors, and parent classes.

## What is an init block?

An `init` block is code that runs [when an object is created](https://kotlinlang.org/docs/classes.html#initializer-blocks). The primary constructor in the class header can only take parameters and set properties. It can't run statements. The `init` block is where those statements go.

```kotlin
class Email(val value: String) {
    init {
        require("@" in value) { "Not an email: $value" }
    }
}

Email("hello")  // IllegalArgumentException: Not an email: hello
```

Now nobody can create an `Email` without an `@`. The check runs for every new object, so the rest of your code can trust it.

An `init` block can also set a `val` that has no value yet. The compiler makes sure it is set exactly once. Set it twice and you get `'val' cannot be reassigned`. Forget it and you get `property must be initialized or be abstract`.

## In what order does init run?

From top to bottom. Properties in the class header, like `val value: String`, are set first. After that, property initializers and `init` blocks run [in the order they appear in the class body](https://kotlinlang.org/docs/classes.html#initializer-blocks), mixed together:

```kotlin
class Profile(name: String) {
    val displayName = name.trim()       // 1
    init { println("first init") }      // 2
    val greeting = "Hi, $displayName"   // 3
    init { println("second init") }     // 4
}
```

You may read that `init` runs "before the rest of the class body". It doesn't. Line 3 runs after the first `init` block. So when the first block runs, `greeting` has no value yet.

![Diagram: what runs when you create an object. 1, the parent class is set up. 2, properties in the class header are set. 3, property initializers and init blocks run from top to bottom. 4, the secondary constructor body runs, if you called one. A property declared below an init block is still empty while that block runs.](https://imayankkumar.com/blog/kotlin-init-block/kotlin-init-block.png align="center")

## Why can a property be null inside init?

Because its line hasn't run yet. If the first `init` block reads `greeting` directly, the compiler stops you with `variable 'greeting' must be initialized`. But the compiler can't see through a function call:

```kotlin
// Almost right: init runs before greeting is set
class Profile(name: String) {
    val displayName = name.trim()

    init {
        println(describe())   // greeting = null
    }

    val greeting: String = "Hi, $displayName"

    fun describe() = "greeting = $greeting"
}

// Right: declare the property first, then the init block
class Profile(name: String) {
    val displayName = name.trim()
    val greeting: String = "Hi, $displayName"

    init {
        println(describe())   // greeting = Hi, Asha
    }

    fun describe() = "greeting = $greeting"
}
```

In bytecode, `greeting` is a plain Java field. Until its line runs, the field holds the JVM default: `null` for objects, `0` for numbers, `false` for booleans. Kotlin's null safety can't help here. The fix is simple: declare properties above the `init` block that uses them.

## Can an init block use a lateinit property?

Yes, it compiles. Whether it works depends on when the property gets a value.

```kotlin
class Settings {
    lateinit var theme: String

    init {
        println(theme)  // crash
    }
}
```

There is no compile error and no warning. It crashes when you create the object, with `UninitializedPropertyAccessException: lateinit property theme has not been initialized`. If the `init` block sets `theme` before reading it, it works. The compiler then tells you `lateinit` isn't needed, because the property is always set in the constructor. For more on this, see [lazy vs lateinit](https://imayankkumar.com/blog/kotlin-lazy-vs-lateinit/).

## How does init work with secondary constructors?

A secondary constructor must call the primary one first, with `this(...)`. So the primary constructor and every `init` block run first. The secondary constructor's body runs last.

```kotlin
class Download(val url: String) {
    init { println("init: $url") }

    constructor() : this("https://example.com/file.zip") {
        println("secondary body")
    }
}

Download()
// init: https://example.com/file.zip
// secondary body
```

Here is the decompiled Java (Kotlin 2.4.21, Vineflower), shortened:

```java
public Download(String url) {
    super();
    this.url = url;
    System.out.println("init: " + this.url);  // init code is here
}

public Download() {
    this("https://example.com/file.zip");     // calls the primary
    System.out.println("secondary body");
}
```

There is no `init()` method. The compiler copies the `init` code into the primary constructor, once. The secondary constructor doesn't get its own copy. It calls the primary one.

You may also read that the compiler copies `init` into every constructor. That only happens when the class has no primary constructor. Then each secondary constructor that calls `super(...)` gets its own copy of every `init` block and property initializer. One that calls `this(...)` doesn't need a copy.

## What runs first, the parent's init or the child's?

The parent's. [The parent class is set up first](https://kotlinlang.org/docs/inheritance.html#derived-class-initialization-order), before any of the child's properties. That leads to a trap:

```kotlin
open class Screen {
    init { println("title = ${title()}") }
    open fun title(): String = "Untitled"
}

class HomeScreen : Screen() {
    private val name = "Home"
    override fun title() = name
}

HomeScreen()  // title = null
```

`Screen`'s `init` calls `title()`, which runs the `HomeScreen` version. But `name` isn't set yet, so you get `null` again. The compiler gives no warning. The Kotlin docs say to avoid calling `open` members from constructors, property initializers and `init` blocks.

## What should you keep out of init?

`init` runs for every object, and you can't skip it or delay it. Keep it small: checks with `require`, and values built from constructor parameters. Keep network calls, disk reads and other slow work out. Use `lazy` for a value you might never need, or a separate function for work with side effects. Your class also stays easy to create in a unit test.

| Feature | Property initializer | init block | Secondary constructor body |
| --- | --- | --- | --- |
| When does it run? | In order, top to bottom | In order, top to bottom, mixed with property initializers | After the primary constructor and all `init` blocks |
| How many can you have? | One per property | Any number | One per secondary constructor |
| Can it run statements? | No, one expression | Yes | Yes |
| Which parameters can it use? | Primary constructor parameters | Primary constructor parameters | Its own parameters |
| Where is it in bytecode? | Inside the primary constructor | Inside the primary constructor | Its own constructor, which calls `this(...)` first |

## Frequently asked questions

**Can a class have more than one init block?** Yes. They run in the order you wrote them, mixed with property initializers. Most classes need one at most.

**Does copy() on a data class run init?** Yes. `copy()` calls the constructor, so your checks run again. If `Price` has `require(amount >= 0)` in `init`, then `Price(10).copy(amount = -1)` throws. More on this in [data class vs regular class](https://imayankkumar.com/blog/kotlin-data-class/).

**Can an object have an init block?** Yes. An `object`'s `init` runs once, [the first time you use it](https://kotlinlang.org/docs/object-declarations.html#behavior-difference-between-object-declarations-and-expressions). A companion object's `init` runs when its outer class is loaded, like a Java static block. See [object](https://imayankkumar.com/blog/kotlin-object/) and [companion object](https://imayankkumar.com/blog/kotlin-companion-object/).

## What should you remember?

`init` blocks and property initializers run together, from top to bottom. A property declared below an `init` block is still empty while that block runs, even if its type can't be null. A secondary constructor's body runs last. A parent's `init` runs before the child's properties are set. Keep `init` short, and declare properties above the code that reads them.

If you want to test yourself, try the [init block interview questions](https://imayankkumar.com/interview/kotlin-init-block/). This post is the fourteenth topic in Stage 1 of my [Android roadmap](https://imayankkumar.com/roadmap/). The previous one is [visibility modifiers](https://imayankkumar.com/blog/kotlin-visibility-modifiers/).

Which `init` block in your code reads a property declared below it?

---

*This post first appeared on* [*imayankkumar.com*](https://imayankkumar.com/blog/kotlin-init-block/)*, where you'll find new posts first.*
