init block in Kotlin
Tags: kotlin, android
Published: 2023-01-03 08:10:55

---
title: init block in Kotlin
published: true
description: In this blog, we will learn about the init block in Kotlin.
tags: kotlin, android
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3axhac25u3jvpqo9utg.png
canonical_url: https://amitshekhar.me/blog/init-block-in-kotlin
---

I am [**Amit Shekhar**](https://amitshekhar.me), a mentor helping developers in getting high-paying tech jobs.

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out [Android Interview Questions and Answers](https://www.youtube.com/playlist?list=PL_I3TGB7aK6jNBMZkw3FYdJXyf7quHdI8).

In this blog, we will learn about the `init` block in Kotlin.

**This article was originally published at [amitshekhar.me](https://amitshekhar.me/blog/init-block-in-kotlin).**

Before jumping into the `init` block, we should know about the `primary` and `secondary` constructors in Kotlin. I will provide a very short introduction to them as these are not the focus of this article.

Let's see an example of the `primary` constructor. Here, we have a `Mentor` class with a `primary` constructor.

```kotlin
class Mentor(firstName: String, lastName: String) {

}
```

And, here we have a `Mentor` class with the `primary` and `secondary` constructor both as below:

```kotlin
class Mentor(firstName: String, lastName: String) {

    constructor(firstName: String, lastName: String, interest: String) : this(firstName, lastName) {
        // inside the secondary constructor
        // code to do something
    }

}
```

Here, we can notice that during the initialization of an instance, we can't write any code to do anything in the `primary` constructor, but we can write the code to do something inside the `secondary` constructor.

**The primary constructor can't contain any code but the secondary constructor can.**

Here, comes the `init` block into the picture. The two things that we can use to put some code to do something during the initialization of an instance are as follows:

- init block
- secondary constructor

**The init block and the secondary constructor can contain any code.**

Now, let's learn about the `init` block in Kotlin.

Here, we have a `Mentor` class with a `primary` constructor and an `init` block.

```kotlin
class Mentor(firstName: String, lastName: String) {

    init {
        val fullName = "$firstName $lastName"
        println(fullName)
    }

}
```

Here, we can notice that we are able to write code inside the `init` block to do something during the initialization.

Question: When does the `init` block get called in Kotlin?

Answer: The `init` block gets called immediately after the `primary` constructor but before the `secondary` constructor.

Things to know while using the `init` block in Kotlin:

- The `init` block gets executed immediately after the `primary` constructor.
- The `init` block gets executed before the `secondary` constructor.
- Primary constructor parameters can be used in the initializer blocks.
- A class can have more than one `init` block, in this case, the initializer blocks are executed in the same order as they appear in the class body considering the properties if there are any in between.
- It does not take any parameters.

Let's take an example to verify the above points.

```kotlin
class Mentor(firstName: String, lastName: String) {

    init {
        println("First init block : $firstName")
    }

    private val fullName = "$firstName $lastName".also { println("FullName property") }

    init {
        println("Second init block : ${fullName.length}")
    }

    constructor(firstName: String, lastName: String, interest: String) : this(firstName, lastName) {
        println("Secondary Constructor: $interest")
    }

}
```

And then, when we create the object of `Mentor` using the `secondary` constructor as below:

```kotlin
Mentor("Amit", "Shekhar", "Technology")
```

This will print the following:

```
First init block : Amit
FullName property
Second init block : 12
Secondary Constructor: Technology
```

When to use the `init` block in Kotlin?

**Answer:** When we have to perform a task during the initialization of an object and we do not have a necessity for a `secondary` constructor. Use the `primary` constructor with the `init` block.

In the Kotlin Android project, we use the `init` block in `ViewModel` as follows:

```kotlin
class NewsListViewModel(private val newsRepository: NewsRepository) : ViewModel() {

    init {
        fetchNews()
    }

    private fun fetchNews() {
        // code to fetch News
    }

}
```

This is how we can use the `init` block in Kotlin.

Watch the video format: [init block in Kotlin](https://www.youtube.com/watch?v=cb3jOFozJns)

Master Kotlin Coroutines from here: [Mastering Kotlin Coroutines](https://amitshekhar.me/blog/kotlin-coroutines)

That's it for now.

Thanks

[**Amit Shekhar**](https://amitshekhar.me)

You can connect with me on:

- [Twitter](https://twitter.com/amitiitbhu)
- [YouTube](https://www.youtube.com/@amitshekhar)
- [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu)
- [GitHub](https://github.com/amitshekhariitbhu)

[**Read all of my high-quality blogs here.**](https://amitshekhar.me/blog)