In Kotlin, an init block runs setup logic when a class instance is created.
It is commonly used to validate constructor arguments, initialize derived properties, or perform other construction-time setup.
class User(val name: String, val age: Int) {
init {
require(name.isNotBlank()) {
"Name must not be blank"
}
require(age >= 0) {
"Age must be non-negative"
}
println("Created user: $name")
}
}
Usage:
val user = User("Alice", 30)
When User("Alice", 30) is called, the init block runs automatically.
Key points
initblocks are part of the class initialization process.- They run after primary constructor parameters are available.
- A class can have multiple
initblocks. - Multiple
initblocks run in the order they appear in the class body. - They are especially useful with primary constructors.
Example with multiple init blocks:
class Rectangle(val width: Int, val height: Int) {
val area: Int
init {
require(width > 0) {
"Width must be positive"
}
}
init {
require(height > 0) {
"Height must be positive"
}
area = width * height
}
}
You can also combine init blocks with property initializers:
class Product(val price: Double) {
val tax = price * 0.2
init {
require(price >= 0) {
"Price cannot be negative"
}
}
}
Initialization happens in the order the declarations appear in the class body, so property initializers and init blocks are executed top to bottom.
