Understanding Init block in Kotlin

In this blog we will learn about about Init block in Kotlin. But, before starting if you are familiar with Java, you must be familiar with the concepts of Constructors.

Constructor is a block of code which get initialised when the object is created.
class SumOfNumbers {
   SumOfNumbers() {
   }
}

In Java, the constructor has the same name as of the class.But in Kotlin we have some thing different for Constructor i.e Primary and Secondary. You can read more about them here.

class Person(name:String,age:Int) {
    
}

This is an example of a Kotlin class having Primary constructor. But like java if we have to perform some task in constructor how can we do that in Kotlin? Because this is not possible in Primary Constructor.

Either we can use secondary constructor or we can use init block. Here, in this block we will talk about the Init Block.

Let us understand init block with an example.

In the above person class we have to check if the person is older then me or not. We can do it using,

class Person(name: String, age: Int) {
    var isOlderThenMe = false
    val myAge = 25

    init {
        isOlderThenMe = age > myAge
    }
}

Here, we have initalised two variables isOlderThenMe and myAge with default value is false and 25.

Now , in the init block, we check the age from the primary constructor with myAge and assign the value to isOlderThenMe. i.e. if the age is greater then 25 value assigned will be true else false.

To check this,

 var person = Person("Himanshu", 20)
 print(person.isOlderThenMe)

This will print the desired result. As when we have initalised the Person class with passing data name as Himanshu and age as 25. The init block will also get called as the object is created and the value of isOlderThenMe has been updated based on the condition.

Points to Note:

  • The init block is always called after the primary constructor
  • A class file can have one or more init blocks executing in series.

Happy learning

Team MindOrks :)

Also, Let’s connect on Twitter, Linkedin, Github, and Facebook.