Sobes.tech
Junior

What is an 'init' block and how is it used in Kotlin?

sobes.tech AI

Answer from AI

The init block is a class initializer in Kotlin. It is executed when an instance of the class is created, after the constructor (both primary and secondary) is called and before the class properties are declared. It is used to execute code necessary for the proper initialization of the object.

Features:

  • A class can have multiple init blocks.
  • init blocks are executed in the order they are declared within the class body.
  • Usually used for validating constructor input parameters, performing calculations, or setting up the initial state of the object.

Example:

class Person(name: String) {
    val formattedName: String

    init {
        // Input validation
        require(name.isNotBlank()) { "Name cannot be blank" }
        // Formatting data for internal use
        formattedName = name.trim().toUpperCase() 
    }

    init {
        // Additional initialization logic if needed
        println("Initializing Person instance with name: $formattedName")
    }
}
What is an 'init' block and how is it used in Kotlin… - sobes.tech