What is init block in Kotlin: Explanation and Example
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.
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) }
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
initblock runs immediately after the primary constructor. - You can have multiple
initblocks; they run in order. - It is useful for validation, logging, or complex initialization.
- It helps keep constructor code clean and organized.
Key Takeaways
init block runs code right after an object is created in Kotlin.init to validate or initialize properties beyond simple assignments.init blocks run in the order they appear in the class.