init block in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
init block in Kotlin

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the 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.

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

}

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

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.

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.

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:

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:

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.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.