Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin

What is an init block in Kotlin?

Umme Ammara

Overview

Whenever we initialize an object, a constructor is called. In Kotlin, there are two types of constructors: primary and secondary. Performing a task is not possible in the primary constructor. For this, we use the secondary constructor or an init block instead. The code written inside the init block is the first one that gets executed when a class is initialized.

Syntax

The init block is initialized using the init keyword. It does not take any parameters.

Let’s look at an example of a class using an init block in the code below:

Example

class Person (name: String, age: Int) {
  init{
    print("Hello, my name is ${name} ")
  }
  init {
      print("I am ${age} years old ")
  }
}

fun main(args: Array<String>) {
  Person("Mike", 22)
}

Note: A class can have multiple init blocks, which get executed sequentially.

Explanation

  • Line 1: We declare a class named Person that takes in two parameters, name and age.
  • Line 2: We declare an init block containing a print statement.
  • Line 5: We declare another init block containing a print statement.
  • Line 11: We initialize the class, passing the value Mike to name and 22 to age.

When the code is run, the print statement in the first init block is executed first, followed by the print statement in the second init block.

RELATED TAGS

kotlin

CONTRIBUTOR

Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring