Google News
logo
Kotlin - Interview Questions
Explain the 'init' block in Kotlin.
In Kotlin, the `init` block is used to initialize the properties or execute code during the initialization phase of an object. It is a special block that is part of a class and is executed when an instance of that class is created. The `init` block is commonly used to perform initialization logic that cannot be achieved through direct property initialization or constructor parameters.

Here's how the `init` block works :

1. Syntax : The `init` block is defined within the body of a class and does not have any explicit keyword. It is denoted by the `init` keyword followed by a code block enclosed in curly braces.
   class MyClass {
       // Properties
       // ...

       // Init block
       init {
           // Initialization code
           // ...
       }
   }​

2. Execution : When an object of the class is created, the `init` block is executed before the constructor body. It allows you to perform any required initialization tasks or computations.

3. Access to Properties : Inside the `init` block, you can access and manipulate the properties of the class, as well as call other functions or perform any necessary operations.
4. Multiple `init` Blocks : A class can have multiple `init` blocks, and they are executed in the order they appear in the class body. This allows you to organize and separate different initialization tasks.

Here's an example that demonstrates the usage of `init` blocks :
class Person(firstName: String, lastName: String) {
    val fullName: String

    init {
        fullName = "$firstName $lastName"
        println("Person initialized")
    }

    init {
        println("Additional initialization logic")
        // Additional initialization code
    }
}

fun main() {
    val person = Person("John", "Doe")
    println(person.fullName)
}​

In the above example, the `Person` class has two `init` blocks. The first `init` block initializes the `fullName` property by concatenating the `firstName` and `lastName` parameters. The second `init` block demonstrates additional initialization logic. When an instance of `Person` is created, both `init` blocks are executed in the order they are defined.

The `init` block is useful for performing complex initialization tasks, initializing properties based on constructor parameters, or executing other required initialization logic before using an object. It provides a way to consolidate initialization code within the class and ensures that it is executed whenever an object is created.
Advertisement