Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.
In this blog, we will learn about the init
block in Kotlin.
This article was originally published at Outcome School.
Before jumping into the init
block, we should know about the primary
and secondary
constructors in Kotlin. I will provide a very short introduction to them as these are not the focus of this article.
Let's see an example of the primary
constructor. Here, we have a Mentor
class with a primary
constructor.
class Mentor(firstName: String, lastName: String) {
}
And, here we have a Mentor
class with the primary
and secondary
constructor both as below:
class Mentor(firstName: String, lastName: String) {
constructor(firstName: String, lastName: String, interest: String) : this(firstName, lastName) {
// inside the secondary constructor
// code to do something
}
}
Here, we can notice that during the initialization of an instance, we can't write any code to do anything in the primary
constructor, but we can write the code to do something inside the secondary
constructor.
The primary constructor can't contain any code but the secondary constructor can.
Here, comes the init
block into the picture. The two things that we can use to put some code to do something during the initialization of an instance are as follows:
- init block
- secondary constructor
The init block and the secondary constructor can contain any code.
Now, let's learn about the init
block in Kotlin.
Here, we have a Mentor
class with a primary
constructor and an init
block.
class Mentor(firstName: String, lastName: String) {
init {
val fullName = "$firstName $lastName"
println(fullName)
}
}
Here, we can notice that we are able to write code inside the init
block to do something during the initialization.
Question: When does the init
block get called in Kotlin?
Answer: The init
block gets called immediately after the primary
constructor but before the secondary
constructor.
Things to know while using the init
block in Kotlin:
- The
init
block gets executed immediately after theprimary
constructor. - The
init
block gets executed before thesecondary
constructor. - Primary constructor parameters can be used in the initializer blocks.
- A class can have more than one
init
block, in this case, the initializer blocks are executed in the same order as they appear in the class body considering the properties if there are any in between. - It does not take any parameters.
Let's take an example to verify the above points.
class Mentor(firstName: String, lastName: String) {
init {
println("First init block : $firstName")
}
private val fullName = "$firstName $lastName".also { println("FullName property") }
init {
println("Second init block : ${fullName.length}")
}
constructor(firstName: String, lastName: String, interest: String) : this(firstName, lastName) {
println("Secondary Constructor: $interest")
}
}
And then, when we create the object of Mentor
using the secondary
constructor as below:
Mentor("Amit", "Shekhar", "Technology")
This will print the following:
First init block : Amit
FullName property
Second init block : 12
Secondary Constructor: Technology
When to use the init
block in Kotlin?
Answer: When we have to perform a task during the initialization of an object and we do not have a necessity for a secondary
constructor. Use the primary
constructor with the init
block.
In the Kotlin Android project, we use the init
block in ViewModel
as follows:
class NewsListViewModel(private val newsRepository: NewsRepository) : ViewModel() {
init {
fetchNews()
}
private fun fetchNews() {
// code to fetch News
}
}
This is how we can use the init
block in Kotlin.
Watch the video format: init block in Kotlin
Master Kotlin Coroutines from here: Mastering Kotlin Coroutines
That's it for now.
Thanks
Amit Shekhar
Co-Founder @ Outcome School
You can connect with me on: