Order of Execution in Kotlin

Vishal
Stackademic
Published in
2 min readFeb 19, 2024

--

When you create an instance of a class in Kotlin, the sequence of initialization is as follows:

  1. init block: The init block is called first, before any constructors (primary or secondary) are executed. This block is used to perform common initialization tasks that are shared across all constructors of the class.

2.Primary Constructor: If the class has a primary constructor, its parameters are initialized next. The primary constructor executes after the init block and before any secondary constructors, if present.

3.Secondary Constructors: If the class has secondary constructors, they are executed after the primary constructor, if it exists. The sequence of execution follows the order in which the secondary constructors are defined in the class.


class MyClass(val name: String) {

init {
println("init block: Initializing MyClass instance with name: $name")
}

constructor(age: Int) : this("unknown") {
println("Secondary constructor: Initializing MyClass instance with age: $age")
}

constructor(name: String, age: Int) : this(name) {
println("Secondary constructor: Initializing MyClass instance with name: $name and age: $age")
}
}

fun main() {
val obj1 = MyClass("John")
val obj2 = MyClass(25)
val obj3 = MyClass("Alice", 30)
}

init block: Initializing MyClass instance with name: John
init block: Initializing MyClass instance with name: unknown
Secondary constructor: Initializing MyClass instance with age: 25
init block: Initializing MyClass instance with name: Alice
Secondary constructor: Initializing MyClass instance with name: Alice and age: 30

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--