Updated April 17, 2023
Introduction to Kotlin init
Kotlin init is one of the blocks and it is used to execute the class is instantiated and the init block is run at every time the class is instantiated with any kind of constructors for to create the objects and called at the main method or wherever it requires the multiple initializer blocks also written with the classes and they will be executed sequentially with the steps like where you can put the codes that will run after properties are to be initialized with same or different orders as they appear in the class body with property initializers.
Syntax
In kotlin language has many default classes, methods, variables and other defined blocks in both customized and in-built areas. Like that, init is the blocks which we can put the codes in the separate area before the class property.
fun main()
{
val n = name()
--some codes—
}
class name{
initialization
init{
---some logic codes—
}
}
The above code is the basic syntax for utilising the init blocks in the kotlin codes. We can also use n number of init blocks which depends on the requirement and the block is initialized before the class properties.
How Kotlin init Work?
The kotlin init is the block which can be placed for the initialization codes the prefixed with the init keyword. During the initialization of an instance, the initializer blocks are to be executed in the same order and they appear in the class body which is interleaved with the property initializers. When we initialize the constructors takes more parts like primary constructor and the parameters can be used in the initializer blocks and also it can be used in the property initializers which declared in the class body and for declaring the properties and initialized them from the primary constructor.
Like that class have the secondary constructors which are prefixed with the constructor and it needs to delegate with the primary constructor either it directly comes or indirectly through the another secondary constructor. The delegation which is of the other constructor in the same class its done using this keyword which becomes part of the primary constructor. In kotlin language delegation is the primary role of the constructor and it happens as the first element of every secondary constructor so that the code is all first initialized the blocks and mentioned the property initializers which is executed before the body of the secondary constructor.
Examples of Kotlin init
Given below are the examples mentioned:
Example #1
Code:
fun main(args: Array<String>) {
val frExam = firstExampleInit("joe", 25)
}
class firstExampleInit(str1: String, intno1: Int) {
val strs: String
var ints: Int
init {
strs = str1.capitalize()
ints = intno1
println("Your init method is called and it stores the string value in the first variable = $strs")
println("The init method is called second variable which is of the integer type = $ints")
val baseNumber = 7
var exp = 6
var out: Long = 4
while (exp != 0) {
out *= baseNumber.toLong()
--exp
}
println("The netoutput result is = $out")
val outpt = Math.pow(baseNumber.toDouble(), exp.toDouble())
var inpNumber = 35
val inpNum2 = 43
while (inpNumber < inpNum2) {
var flag = false
for (i in 2..inpNumber / 3) {
if (inpNumber % i == 0) {
flag = true
break
}
}
if (!flag)
print("$inpNumber ")
++inpNumber
}
val xy = 'S'
when {
(xy in 'a'..'z' || xy in 'A'..'Z') -> println("Your input $xy is an alphabet.")
else -> println("Your input $xy is not an alphabet.")
}
val nubers = 13
var i = 1
while (i <= 13) {
val tble = nubers * i
println("User based on your input number the multiplication of table is $nubers * $i = $tble")
i++
}
}
}
Output:
Explanation:
- In the above example, we used the init { } blocks in various sequences. First, we created the class and passing some parameters like string and integer type format variables and it’s been used only to specify the datatype values.
- Then we initialize the blocks using the init keyword in that we can declare the variables with the specified format and values than using the loop statement datas are iterated and specified the conditions like xy in ‘a..z’ || xy in ‘A..Z’ using these character formats also we use the pipe symbol and or condition for to validate the datas.
- Finally using the main method, we can create the object of the class and print the method values on the console screen.
Example #2
Code:
class MultiInit(name: String) {
init {
println("First initializer block that prints ${name}")
val nums = listOf(10, 20, 30, 40, 50, 60, 70, 80, 90,100 )
val ascOrder = nums.sorted()
println(ascOrder)
val descOrder = nums.sortedDescending()
println(descOrder)
val numLists = listOf(70, 40, 20, 10, 30, 50, 60, 80, 90,100 )
val outp = numLists.contains(5)
if (outp)
println("Your input number contains 5")
else
println("Your input number does not contain 5")
}
init {
println("Second initializer block that prints ${name.length}")
val HAppliance = listOf("Bed", "Pillows", "Cort", "Locker", "Travel Bag", "Wall watch", "Cleaning equipments")
for (k in HAppliance) {
print("$k, ")
}
println()
for (i in 0 until HAppliance.size) {
print("${HAppliance[i]} ")
}
println()
HAppliance.forEachIndexed({i, j -> println("Home Appliances[$i] = $j")})
val it: ListIterator<String> = HAppliance.listIterator()
while (it.hasNext()) {
val i = it.next()
print("$i ")
}
println()
}
}
fun main(args: Array<String>) {
var multi = MultiInit("Welcome To My Domain its a second example that related to the kotlin init concepts")
}
}
Output:
Explanation:
- In the second example, we used multi inits in the kotlin class and it is used for loops to iterate the user datas in the class.
- Here we used the list collection interface in the one in inits block and another init block we performed the ascending and descending operations. We created an instance and called in the main method.
Conclusion
In kotlin language, we used different concepts to implement the application like that init is one of the block types and it is mainly used to store and execute the data. Every time the class is instantiated the init block is executed with any kind of constructors with sequential order.
Recommended Articles
This is a guide to Kotlin init. Here we discuss the introduction, syntax, and working of init in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –