Init block in Kotlin

itAgenturen Android Kotlin development engineer senior utvecklare sweden

It is essential to know about the primary and secondary constructors in Kotlin before we jump into the init block.

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

itAgenturen Android Engineer consultant development sweden

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

itAgenturen Kotlin Android Engineer Development Consultant Sweden Mobile App

A primary constructor can't be used to do anything during instance initialization, but a secondary constructor can accomplish something.

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 Person class with a primary constructor and an init block.

itAgenturen Kotlin Android Engineer Development Consultant Sweden Mobile App

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

When does the init block get called in Kotlin?

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.


When to use the init block in Kotlin?

When we have to perform a task during the initialization of an object, 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:


itAgenturen Kotlin Android Engineer Development Consultant Sweden Mobile App



Previous
Previous

International Women's Day

Next
Next

ChatGPT (Open AI)