androidengineers.Book a session
โ† All interview questions
KotlinIntermediate4 min

What is an Init block in Kotlin?

Answer

The init block is an initializer block in Kotlin classes.

Functionality

  • It runs immediately after the primary constructor.
  • It is used to run startup logic that requires the class properties to be initialized.
  • You can have multiple init blocks; they execute in the order they appear in the class body.
  • It is often used because the primary constructor cannot contain code (only property declarations).

Example

class User(val name: String) {
    val upperName: String
    
    init {
        println("Initializing User: $name")
        upperName = name.uppercase()
    }
}

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising