Kotlin Initializer Blocks Tutorial

In this section, we will learn what the initializer block is and how it works in Kotlin.

What is Initializer Block in Kotlin?

So far, we’ve seen that when we want to initialize the properties of an object, we can set a set of parameters for the constructor of a class and assign their values as the values of the properties.

This is just a simple assignment, and it’s good when there’s no need for value checking and basically when we’re in a safe environment!

But what if the situation changed, and we needed to check the values assigned to the parameters before passing them to the properties of an object?

You can’t use a function at the time of object creation and also you can’t put if-else statement right in the body of a class (outside of any function)!

So to solve this problem, Kotlin provided something that is called initializer block!

This is a block that will be invoked right after calling a constructor at the time of object creation.

So using this block, we can put any sort of instructions in its body and it is guaranteed to be executed right after the call to the constructor and before the process of creating an object is complete.

Kotlin Initializer Blocks Syntax:

This is the syntax of creating an initializer block in a class:




To create an initializer, we use the init keyword and after that put a pair of braces {} which defines the body of the initializer where we can put instructions to be executed.

Note that you can have one or more initializer in a class and they all will be executed one after the other from top to bottom.

Example: creating initializer block in Kotlin

class Employee (fName:String, lName:String, ag:Int){

        println("Initializing the properties of the current object")
    var firstName:String 
    var lastName:String 
    var age:Int

        firstName = fName
        lastName = lName
        age = ag 
        println("The properies of the object is now initialized")

fun main(){
    var emp = Employee("John","Doe",21)







How does initializer block work in Kotlin?

Here we have two initializers in the Employee class.

The first one is set on top of the class with one simple message to the output stream and the other one comes after the declaration of the properties.

Note: when creating initializer in a class, if the properties in that class are initialized in the body of the initializer block, then you don’t need to assign an initial value for the properties anymore!


Top Technologies