0
0
KotlinConceptBeginner · 3 min read

What is init block in Kotlin: Explanation and Example

In Kotlin, the init block is a special block inside a class that runs code when an object is created. It is used to initialize the class or run setup code right after the primary constructor executes.
⚙️

How It Works

The init block in Kotlin acts like a setup step that runs automatically when you create an object from a class. Think of it like unpacking and arranging your new phone right after you buy it — the phone is the object, and the init block is the process of turning it on and setting it up.

When you create an instance of a class, Kotlin first runs the primary constructor to set up the basic properties. Then, it runs the init block(s) in the order they appear. This lets you add extra steps like checking values or printing messages right after the object is ready.

You can have multiple init blocks in one class, and they will run one after another. This helps organize initialization code into smaller parts if needed.

💻

Example

This example shows a class with an init block that prints a message when an object is created.

kotlin
class Person(val name: String, val age: Int) {
    init {
        println("Creating a person named $name who is $age years old.")
    }
}

fun main() {
    val person = Person("Alice", 30)
}
Output
Creating a person named Alice who is 30 years old.
🎯

When to Use

Use the init block when you want to run code right after an object is created, especially if you need to:

  • Check or validate constructor parameters
  • Initialize properties that require logic beyond simple assignment
  • Print or log information about the new object
  • Run setup code that depends on constructor values

For example, if you want to ensure an age is positive or print a welcome message when a user object is created, the init block is a good place to do this.

Key Points

  • The init block runs immediately after the primary constructor.
  • You can have multiple init blocks; they run in order.
  • It is useful for validation, logging, or complex initialization.
  • It helps keep constructor code clean and organized.

Key Takeaways

The init block runs code right after an object is created in Kotlin.
Use init to validate or initialize properties beyond simple assignments.
Multiple init blocks run in the order they appear in the class.
It helps keep initialization logic organized and separate from constructor parameters.